精简易用的log4net使用
log4net是不错的组件,但如果长时间不用,之前研究通透的东西就忘记了。重要的日志会另外做,但只是想快速的让自己的程序记录一些出错信息等, log4net是不错的选择,关键是能精简和易用。
下面记录log4net快速稳定的使用方法:
1.项目引用log4net.dll
2.App.config中加入配置信息
上图1区,configSectios只能放在最前边,不然会报错,它只能成为第一个子节项。2区是配置项,可以默认就好。
3.代码,
using System; using System.Collections.Generic; using System.Text; using log4net; using log4net.Config; namespace TestLog4net { public static partial class Log { /// <summary> /// 日志类 /// </summary> private static ILog clientLog; /// <summary> /// 初始化 /// </summary> static Log() { XmlConfigurator.Configure(); if (clientLog == null) clientLog = LogManager.GetLogger(typeof(Log)); } /// <summary> /// 写普通信息 /// </summary> /// <param name="msg">消息</param> public static void WriteInfo(string msg) { clientLog.Info(msg); } /// <summary> /// 写调试信息 /// </summary> /// <param name="msg">消息</param> public static void WriteDebug(string msg) { clientLog.Debug(msg); } /// <summary> /// 写错误信息 /// </summary> /// <param name="msg">消息</param> /// <param name="ex">异常</param> public static void WriteError(string msg, Exception ex) { clientLog.Error(msg, ex); } /// <summary> /// 写错误信息 /// </summary> public static void WriteError(string msg) { clientLog.Error(msg); } /// <summary> /// 写Warn信息 /// </summary> public static void WriteWarn(string msg) { clientLog.Warn(msg); } } }
4.调用方法,很简单,静态类不用初始化什么的,直接用就行。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using log4net; using log4net.Config; namespace TestLog4net { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Log.WriteDebug("my debug"); } private void button2_Click(object sender, EventArgs e) { Log.WriteInfo("info test"); } private void button3_Click(object sender, EventArgs e) { try { throw(new Exception("Error:length=0 test")); } catch (Exception ex) { Log.WriteError("demo of error", ex); } } } }