Log4net 是.Net下一个非常优秀的开源日志记录组件。Log4net记录日志的功能非常强大。它可以将日志分不同的等级,以不同的格式,输出到不同的媒介。
由于业务需要,计划为日志增加2个字段,除了Log4net默认字段,额外增加了LOG_TYPE 和 LOG_OPERATOR 两个字段用于对日志分类和记录相关操作的人员,以便于检索。
本文方法参考了StackOverFlow问答中的内容(https://stackoverflow.com/questions/12139486/log4net-how-to-add-a-custom-field-to-my-logging),
此方法并不需要创建额外的类,使用非常简单。
1、创建数据库表
针对写入数据库的情况,如果写入文本无需创建数据表。
CREATE TABLE [dbo].[SYS_LOG1]( [LOG_ID] [int] IDENTITY(1,1) NOT NULL, [LOG_DATE] [nvarchar](255) NULL, [LOG_THREAD] [nvarchar](255) NULL, [LOG_LEVEL] [nvarchar](50) NULL, [LOG_LOGGER] [nvarchar](255) NULL, [LOG_MESSAGE] [nvarchar](4000) NULL, [LOG_EXCEPTION] [nvarchar](2000) NULL, [LOG_TYPE] [nvarchar](50) NULL, [LOG_OPERATOR] [nvarchar](50) NULL, CONSTRAINT [PK_SYS_LOG2] PRIMARY KEY CLUSTERED ( [LOG_ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
2、添加Log4net 配置AdoNetAppender节点
注意加粗的部分设计自定义字段的配置
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender"> <bufferSize value="1" /> <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <connectionString value="data source=127.0.0.1;initial catalog=JXFST_WMS;integrated security=false;persist security info=True;User ID=sa;Password=123" /> <commandText value="insert into SYS_LOG1 (LOG_DATE,LOG_THREAD,LOG_LEVEL,LOG_LOGGER,LOG_MESSAGE,LOG_EXCEPTION,LOG_TYPE,LOG_OPERATOR) values (@log_date, @thread, @log_level, @logger, @message, @exception, @log_type, @log_operator)" /> <parameter> <parameterName value="@log_date" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout" > <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss.ffff}" /> </layout> </parameter> <parameter> <parameterName value="@thread" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%thread" /> </layout> </parameter> <parameter> <parameterName value="@log_level" /> <dbType value="String" /> <size value="50" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%level" /> </layout> </parameter> <parameter> <parameterName value="@logger" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger" /> </layout> </parameter> <parameter> <parameterName value="@message" /> <dbType value="String" /> <size value="4000" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message" /> </layout> </parameter> <parameter> <parameterName value="@exception" /> <dbType value="String" /> <size value="2000" /> <layout type="log4net.Layout.ExceptionLayout" /> </parameter> <parameter> <parameterName value="@log_type" /> <dbType value="String" /> <size value="50" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{LogType}" /> </layout> </parameter> <parameter> <parameterName value="@log_operator" /> <dbType value="String" /> <size value="50" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{LogOperator}" /> </layout> </parameter> </appender>
3、使用Log4net的上下文来将值传递给参数
//传参 log4net.LogicalThreadContext.Properties["LogType"] = "Custom LogType"; log4net.LogicalThreadContext.Properties["LogOperator"] = "Custom log_operator"; //写日志 Program.sysLog.WarnFormat("TaskCompleteJob.Execute:处理Control任务失败 {0}", sResult);
或者干脆封装几个方法,取代Log4net原有的方法。
/// <summary> /// 自定义写入日志方法 /// </summary> /// <param name="logType">日志类别</param> /// <param name="logOperator">日志操作者</param> /// <param name="logMessage">日志信息</param> public void YwzWarn(string logType,string logOperator ,string logMessage) { log4net.LogicalThreadContext.Properties["LogType"] = logType; log4net.LogicalThreadContext.Properties["LogOperator"] = logOperator; Program.sysLog.Warn(logMessage); } /// <summary> /// 自定义写入日志方法 /// </summary> /// <param name="logType">日志类别</param> /// <param name="logOperator">日志操作者</param> /// <param name="logMessage">日志信息</param> /// <param name="exception">异常信息</param> public void YwzWarn(string logType, string logOperator, string logMessage, Exception exception) { log4net.LogicalThreadContext.Properties["LogType"] = logType; log4net.LogicalThreadContext.Properties["LogOperator"] = logOperator; Program.sysLog.Warn("TaskCompleteJob.Execute:处理Control任务失败", exception); } /// <summary> /// 自定义写入日志方法 /// </summary> /// <param name="logType">日志类别</param> /// <param name="logOperator">日志操作者</param> /// <param name="messageFormat">日志信息</param> /// <param name="args">格式化参数</param> public void YwzWarnFormat(string logType, string logOperator, string messageFormat, params object[] args) { log4net.LogicalThreadContext.Properties["LogType"] = logType; log4net.LogicalThreadContext.Properties["LogOperator"] = logOperator; Program.sysLog.WarnFormat("TaskCompleteJob.Execute:处理Control任务失败_{0}", args); }
调用就变的更简单了。
this.YwzWarn("Task", "路人甲", "TaskCompleteJob.Execute:处理Control任务失败"); this.YwzWarn("Task", "路人甲", "TaskCompleteJob.Execute:处理Control任务失败",new Exception("发生异常啦")); this.YwzWarnFormat("Task", "路人甲", "TaskCompleteJob.Execute:处理Control任务失败_{0}", "12344321abcddcba");
效果如下图。
原文地址:https://www.cnblogs.com/ywzdmu/p/9858389.html
时间: 2024-10-25 08:56:04