Log4Net是常用的功能强大的日志插件,该插件提供了几个默认字段
大家可能都用过Log4Net插件来记录日志,该插件默认提供了这几个字段@log_date, @thread, @log_level, @logger, @message, @exception, 但有时这几个字段不能满足我们记录日志的需求,需要扩展我们所需的其他字段,并记录到数据库。比如,我需要记录UserID,UnitCode,MenuID,OperateType等。下面按步骤介绍一下如何在Log4Net组件下,自定义字段并保存到数据库:
第一步:在数据库日志表中添加自定义字段
第二步:创建Custom实体ActionLoggerInfo
public class ActionLoggerInfo { public int UserID { get; set; } public string UnitCode { get; set; } public int MenuID { get; set; } public int OperaterType { get; set; } public string sMessage { get; set; } public ActionLoggerInfo(int userId, string unitCode, int menuId, int operaterType,string smessage) { this.UserID = userId; this.UnitCode = unitCode; this.MenuID = menuId; this.OperaterType = operaterType; this.sMessage = smessage; } }
第三步:创建Custom转换器ActionConverter
/*命名空间引用*/using log4net;using log4net.Layout;using log4net.Layout.Pattern;using log4net.Core;/*代码*/public class ActionConverter : PatternLayoutConverter { protected override void Convert(System.IO.TextWriter writer, LoggingEvent loggingEvent) { var actionInfo = loggingEvent.MessageObject as ActionLoggerInfo; if (actionInfo == null) { writer.Write(""); } else { switch (this.Option.ToLower()) { case "userid": writer.Write(actionInfo.UserID); break; case "unitcode": writer.Write(actionInfo.UnitCode); break; case "menuid": writer.Write(actionInfo.MenuID); break; case "operatertype": writer.Write(actionInfo.OperaterType); break; case "smessage": writer.Write(actionInfo.sMessage); break; default: writer.Write(""); break; } } } }
第四步:创建ActionLayoutPattern
/*命名空间引用*/using log4net;using log4net.Layout;using log4net.Layout.Pattern;using log4net.Core;/*代码*/public class ActionLayoutPattern : PatternLayout { public ActionLayoutPattern() { this.AddConverter("actionInfo", typeof(ActionConverter)); } }
第五步:配置log4net.config
第六步:创建Log日志帮助类,LogUtil
public class LogUtil{ public LogUtil() { } private static ActionLoggerInfo _message = null; private static log4net.ILog _log; public static log4net.ILog Log { get { if (_log == null) { _log = LogManager.GetLogger("OperateLogger"); } return _log; } } public static void Debug() { if (Log.IsDebugEnabled) { Log.Debug(_message); } } public static void Error() { if (Log.IsErrorEnabled) { Log.Error(_message); } } public static void Fatal() { if (Log.IsFatalEnabled) { Log.Fatal(_message); } } public static void Info() { if (Log.IsInfoEnabled) { Log.Info(_message); } } public static void Warn() { if (Log.IsWarnEnabled) { Log.Warn(_message); } } public static void SaveMessage(int userId, string unitCode, int menuId, int operaterType,string smessage,int level) { _message = new ActionLoggerInfo(userId, unitCode, menuId, operaterType, smessage); switch (level) { case 1: Info(); break; case 2: Warn(); break; case 3: Error(); break; case 4: Fatal(); break; default: break; } }}
第七步:在具体页面上调用SaveMessage方法,写入日志