Log4Net 添加自定义字段并保存到数据库

时间:2022-04-26 02:37:10

Log4Net是常用的功能强大的日志插件,该插件提供了几个默认字段

大家可能都用过Log4Net插件来记录日志,该插件默认提供了这几个字段@log_date, @thread, @log_level, @logger, @message, @exception, 但有时这几个字段不能满足我们记录日志的需求,需要扩展我们所需的其他字段,并记录到数据库。比如,我需要记录UserID,UnitCode,MenuID,OperateType等。下面按步骤介绍一下如何在Log4Net组件下,自定义字段并保存到数据库:

第一步:在数据库日志表中添加自定义字段

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

<appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
    <bufferSize value="1" />
    <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <connectionString value="DATABASE=AT_GGJPlat3;SERVER=192.168.**.***;UID=**;PWD=***;Connect Timeout=15;" />
    <commandText value="INSERT INTO *****Log([dtDate],[sThread],[sLevel],[sLogger],[sMessage],[sException],[UserID],[UnitCode],[MenuID],[OperaterType]) 
VALUES (@log_date, @thread, @log_level, @logger, @message, @exception,@userid,@unitcode,@menuid,@operatertype)"
/> <parameter> <parameterName value="@log_date" /> <dbType value="DateTime" /> <layout type="log4net.Layout.RawTimeStampLayout" /> </parameter> <parameter> <parameterName value="@thread" /> <dbType value="String" /> <size value="100" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%t" /> </layout> </parameter> <parameter> <parameterName value="@log_level" /> <dbType value="String" /> <size value="200" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%p" /> </layout> </parameter> <parameter> <parameterName value="@logger" /> <dbType value="String" /> <size value="500" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger" /> </layout> </parameter> <parameter> <parameterName value="@message" /> <dbType value="String" /> <size value="3000" /> <layout type="ProvincePlat.CommonClass.Logger.ActionLayoutPattern"> <conversionPattern value="%actionInfo{smessage}"/> </layout> </parameter> <parameter> <parameterName value="@exception" /> <dbType value="String" /> <size value="4000" /> <layout type="log4net.Layout.ExceptionLayout" /> </parameter> <parameter> <parameterName value="@userid" /> <dbType value="Int32"/> <layout type="ProvincePlat.CommonClass.Logger.ActionLayoutPattern"> <conversionPattern value="%actionInfo{userid}"/> </layout> </parameter> <parameter> <parameterName value="@unitcode" /> <dbType value="String" /> <size value="10" /> <layout type="ProvincePlat.CommonClass.Logger.ActionLayoutPattern"> <conversionPattern value="%actionInfo{unitcode}"/> </layout> </parameter> <parameter> <parameterName value="@menuid" /> <dbType value="Int32"/> <layout type="ProvincePlat.CommonClass.Logger.ActionLayoutPattern"> <conversionPattern value="%actionInfo{menuid}"/> </layout> </parameter> <parameter> <parameterName value="@operatertype" /> <dbType value="Int32"/> <layout type="ProvincePlat.CommonClass.Logger.ActionLayoutPattern"> <conversionPattern value="%actionInfo{operatertype}"/> </layout> </parameter> </appender>

第六步:创建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方法,写入日志