//==============================================================
//  版权所有：深圳杰文科技
//  文件名：SystemLogger.cs
//  版本：V1.0  
//  创建者：Jay  ( QQ： 85363208 )
//  创建时间：2017-11-28 16:18
//  创建描述：
//  修改者：
//  修改时间：
//  修改说明： 
//==============================================================

using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace Infrastructure.Log
{
	public class SystemLogger
	{
		public static readonly SystemLogger Instance = new SystemLogger();

		private static readonly Logger _Logger = null;

		private static bool _IsTracing = false;

		public static bool IsDebug = false;

		static SystemLogger()
		{
			string logPath = ConfigurationManager.AppSettings["ServiceLogPath"];
			if (string.IsNullOrEmpty(logPath)) //如果app.config没有配置日志路径，那么不记录系统日志。
			{
				_IsTracing = false;
				return;
			}

			_IsTracing = Directory.Exists(logPath);
			if (_IsTracing)
			{
				//_Logger = new DailyLogger(logPath, "ServiceInvokeLog");
				_Logger = new HourlyLogger(logPath, "ServiceInvokeLog");
			}
		}

		public void WriteAction(string id, string action)
		{
			RealWrite(id, action);
		}

		public void WriteSql(string id, string sql)
		{
			RealWrite(id, sql);
		}

		public void WriteError(Exception error)
		{
			string ip = GetCurrentAddress();
			WriteError(ip, error);
		}

		public void WriteError(string id, Exception error)
		{
			if (error is ServiceException)
			{
				ServiceException se = error as ServiceException;
				if (se.Code != 0)
				{
					RealWrite(id, string.Format("Error Code：{0}", se.Code));
				}
			}
			Exception ex = error.InnerException ?? error;
			string content = string.Format("{0}：{1}", ex.GetType(), ex.Message, ex.StackTrace);

			RealWrite(id, content);
		}

		//public void Write(string id, string msg, params object[] args)
		//{
		//	RealWrite(id, string.Format(msg, args));
		//}

		public void Write(string id, string msg)
		{
			RealWrite(id, msg);
		}

		private void RealWrite(string id, string msg)
		{
			//string address = GetCurrentAddress();
			//if (!string.IsNullOrEmpty(address))
			//{
			//	address = address + "  ";
			//}

			msg = string.Format("【{0}({1})】{2}", DateTime.Now.ToString("HH:mm:ss.fff"), id, msg);

			Console.WriteLine(msg);

			if (IsDebug)
			{
				Debug.WriteLine(msg);
			}

			if (_IsTracing)
			{
				_Logger.Write(msg);
			}
		}

		public void Close()
		{
			if (_Logger != null)
			{
				_Logger.Close();
			}
		}

		private string GetCurrentAddress()
		{
			OperationContext context = OperationContext.Current; //提供方法执行的上下文环境。
			if (context == null)
			{
				return "";
			}
			MessageProperties properties = context.IncomingMessageProperties; //获取传进的消息属性。
			RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; //获取消息发送的远程终结点IP和端口。
			return endpoint.Address;
		}
	}
}
