`

a minilog for .net

    博客分类:
  • C#
 
阅读更多
/*
 * Created by SharpDevelop.
 * User: f
 * Date: 2015/1/29
 * Time: 15:30
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
//#define IsConfig
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Configuration;
using System.Threading;
using System.Reflection;
namespace Log
{
	/// <summary>
	/// Description of Log.
	/// </summary>
	public class Log
	{
		private static TraceSwitch ts;
		
		private Log()
		{
			
		}
		static Log()
		{
			init();
		} 
		private static bool IsError
		{
			get{return ts.TraceError;}
		}
		private static bool IsInfo
		{
			get{return ts.TraceInfo;}
		}
		private static bool IsDebug
		{
			get{return ts.TraceVerbose;}
		}
		private static bool IsWarn
		{
			get{return ts.TraceWarning;}
		}
		
		private static void WriteLine(String message,String category,String className)
		{
			String output=String.Format("{0}  {1}  {2}  {3}",category,DateTime.Now,className,message);
			WriteLine(output);
		}
		
		private static void WriteLine(String message,String category)
		{
			WriteLine(message,category,GetCallClass());
		}
		
		private static void WriteLine(String message)
		{
			Trace.WriteLine(message);
		}
		
		
		public static void Warn(String message)
		{
			if(IsWarn)
				WriteLine(message,"WARN ");
			
		}
		public static void Debug(String message)
		{
			if(IsDebug)
				WriteLine(message,"DEBUG");
		}
		public static void Info(String message)
		{
			if(IsInfo)
				WriteLine(message,"INFO ");
		}
		public static void Error(String message)
		{
			if(IsError)
				WriteLine(message,"ERROR");
		}
		public static void Warn(String message,object[] param)
		{
			Warn(getFormatMessage(message,param));
		}
		public static void Debug(String message,object[] param)
		{
			Debug(getFormatMessage(message,param));
		}
		public static void Info(String message,object[] param)
		{
			Info(getFormatMessage(message,param));
		}
		public static void Error(String message,object[] param)
		{
			Error(getFormatMessage(message,param));
		}
		
		
		
		public static void Warn(String message,Exception e)
		{
			if(IsWarn)
			{
				WriteLine(getExceptionMessage(message,e),"WARN ",GetCallClass(e));
			}
			
		}
		public static void Debug(String message,Exception e)
		{
			if(IsDebug)
			{
				WriteLine(getExceptionMessage(message,e),"DEBUG",GetCallClass(e));
			}
		}
		public static void Info(String message,Exception e)
		{
			if(IsInfo)
			{
				WriteLine(getExceptionMessage(message,e),"INFO ",GetCallClass(e));
			}
		}
		public static void Error(String message,Exception e)
		{
			if(IsError)
			{
				WriteLine(getExceptionMessage(message,e),"ERROR",GetCallClass(e));
			}
		}
		
		public static void Warn(String message,object[] param,Exception e)
		{
			Warn(getFormatMessage(message,param),e);
		}
		public static void Debug(String message,object[] param,Exception e)
		{
			Debug(getFormatMessage(message,param),e);
		}
		public static void Info(String message,object[] param,Exception e)
		{
			Info(getFormatMessage(message,param),e);
		}
		public static void Error(String message,object[] param,Exception e)
		{
			Error(getFormatMessage(message,param),e);
		}
		
		
		private static String getFormatMessage(String message,object[] param)
		{
			return String.Format(message,param);
		}
		
		private static String getExceptionMessage(String message,Exception e)
		{
			return String.Format("{0} [{1},{2}]",message,e.Message,e.StackTrace);
		}
		
		
		private static System.Threading.ThreadLocal<DateTime> local=new ThreadLocal<DateTime>();
		public static void setTime()
		{
			local.Value=DateTime.Now;
		}
		public static long GetDiff()
		{
			if(local.IsValueCreated)
			{
				return (DateTime.Now-local.Value).Milliseconds;
			}
			return 0;
		}
		public static void WriteDiff()
		{
			Trace.WriteLine("the time diff:"+GetDiff());
		}
		
		
		private static String SWITCHNAME="miniLogSwitch";
		private static void init()
		{
			
			#if IsConfig
			ConfigurationSection section=GetConfigSection();
			bool contain=false;
			if(section!=null)
			{
				SwitchAttribute[] attrs=SwitchAttribute.GetAll(Assembly.GetExecutingAssembly());
				foreach(SwitchAttribute attr in attrs)
				{
					if(SWITCHNAME.Equals(attr.SwitchName))
					{
						ts=new TraceSwitch(SwitchName,"default mini switch");
						contain=true;
						break;
					}
				}
			}
			if(!contain)
			{
				ts=new TraceSwitch(SWITCHNAME,"default mini switch");
				ts.Level=TraceLevel.Verbose;//默认输出全部
				initListeners();
				
			}
			#else
				ts=new TraceSwitch(SWITCHNAME,"default mini switch");
				ts.Level=TraceLevel.Verbose;//默认输出全部
				initListeners();
			#endif
			
		}
		
		
		/// <summary>
		/// get top frame 获取调用者的当前类
		/// from https://github.com/NLog/NLog/blob/master/src/NLog/LogFactory.cs
		/// </summary>
		/// <returns></returns>
		[MethodImpl(MethodImplOptions.NoInlining)]
        private static String GetCallClass(Exception e)
        {
        	var start=DateTime.Now;
        	if(e!=null)
        	{
        		return e.TargetSite.DeclaringType.FullName;
        	}
        	StackFrame frame=new StackFrame(4,false);
        	String result=frame.GetMethod().DeclaringType.FullName;
        	return result;
			
        }
        private static String GetCallClass()
        {
        	return GetCallClass(null);
        }
		
		private static ConfigurationSection GetConfigSection()
    	{
			return (ConfigurationSection)ConfigurationManager.GetSection("system.diagnostics");
    	}

		private static void initListeners()
		{
			TextWriterTraceListener text = new TextWriterTraceListener(System.AppDomain.CurrentDomain.BaseDirectory + "/log.txt");
			text.TraceOutputOptions=TraceOptions.DateTime;
			Trace.Listeners.Add(text);
		}
	}
}

 

/*
 * Created by SharpDevelop.
 * User: f
 * Date: 2015/1/30
 * Time: 16:11
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Web;
namespace Log.Test
{
	/// <summary>
	/// test Log.class
	/// </summary>
	public class TestLog
	{
		private delegate void TestDele();
		public TestLog()
		{
		}
		
		public void TestAsync()
		{
			
			TestDele del=new TestDele(TestDeleMethod);
			del.BeginInvoke(new AsyncCallback(TestCallBack),del);
		}
		public void TestDeleMethod()
		{
			var start=DateTime.Now;
			Log.Debug("TestDeleMethod");
			var diff=(DateTime.Now-start).Milliseconds;
        	Console.Error.WriteLine("diff1:"+diff);
			try
			{
				Object a=null;
				Object abc=a.Equals("b");
			}catch(Exception e)
			{
				var start1=DateTime.Now;
				Log.Info("abc exception",e);
				var diff1=(DateTime.Now-start).Milliseconds;
				Console.Error.WriteLine("diff2:"+diff);
			}
		}
		public void TestCallBack(IAsyncResult result)
		{
			try
			{
				TestDele del=(TestDele)(result.AsyncState);
				del.EndInvoke(result);
				Log.Warn("call back");
			}catch(Exception e)
			{
				Log.Warn("call back error",e);
			}
			
		}	
	}
}

 

INFO    2015/1/30 17:16:40  the time diff:1
DEBUG  2015/1/30 17:16:40  Log.Test.TestLog  TestDeleMethod
INFO    2015/1/30 17:16:40  Log.Test.TestLog  abc exception [未将对象引用设置到对象的实例。,   在 Log.Test.TestLog.TestDeleMethod() 位置 e:\Users\c#\Log\Log\Log\Test\TestLog.cs:行号 38]
WARN  2015/1/30 17:16:40  Log.Test.TestLog  call back

 

分享到:
评论

相关推荐

    miniLog php log日志类

    1. **配置简便**:miniLog强调“少配置或零配置”,这意味着在大多数情况下,开发者无需进行复杂的设置就可以开始使用。只需引入该类库,即可快速实现日志记录功能,大大减少了开发时间。 2. **兼容多种数据格式**...

    PyPI 官网下载 | minilog-1.2.6.tar.gz

    《PyPI上的minilog-1.2.6:Python日志管理与分布式系统结合的实践》 在Python的生态系统中,PyPI(Python Package Index)是开发者获取和分享开源软件包的重要平台。本文将深入探讨PyPI上的一款名为minilog的库,其...

    Python库 | minilog-1.4.tar.gz

    资源分类:Python库 所属语言:Python 资源全名:minilog-1.4.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    minilog:具有Stream-API后端的轻量级客户端和服务器端日志记录

    与Node和浏览器控制台的接口兼容性,也就是说,您可以用Minilog替换console.*调用,因为它支持( .log , .debug , .info , .warn和.error ) 每个日志消息都可以与一个名称空间关联。 日志输出可以按名称空间和...

    minilog:用于Python日志记录的简约包装器

    小日志 Python的简约日志记录包装器。 用法 每个项目都应使用日志记录,但是对于简单的用例,这需要太多样板。 而不是将所有这些都包含在您的模块中: import logging log = logging ....def greet ( name ): ...

    Python库 | minilog-1.1.tar.gz

    资源分类:Python库 所属语言:Python 资源全名:minilog-1.1.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    适用于log4j的Windows日志查看器-.NET开发

    Logazmic Minilog的nlog日志查看器。 目前仅支持log4j xml布局。 核心基于Log2console。 在WPF中使用MahApps重写UI。地铁支持:侦听tcp / udp打开* .log4j f Logazmic Minilog日志查看器,用于nlog。 目前仅支持log4...

    linux-minio安装.docx

    在Linux后台启动MinIO,可以指定端口和数据目录,同时将日志重定向到文件`minilog.log`: ```bash $ ./minio server /app/xsbank/servers/middleware/minio/data &gt; minilog.log & ``` 这里,`/app/xsbank/servers/...

    transform-runner:接受一组文件,对它们应用转换并返回可以转换为包的 JSON 输出

    变换跑步者 接受一组文件,对它们... log: Minilog('runner'), include: [ '/home/foo/index.js' ], exclude: [ // /^.+(?!\.js).{3}$/i, '/home/foo/node_modules', ], jobs: require('os').cpus().length * 2,

Global site tag (gtag.js) - Google Analytics