http://www.cnblogs.com/Arlen/archive/2008/11/22/1338908.html
本贴在原来帖子的基础上有些修改,经过本人的实际运行调试运行,本贴中的代码都可以直接复制使用。
在项目中需要记录业务日志(即用户进行了什么操作,操作什么内容,什么时候,操作内容以结构化的方式存储,以方便以后数据挖掘)。
系统采用了log4net来将业务日志记录到数据库中,反正在log4net中加个Appender就可以。由于业务需要记录的并不是简单的系统时间%date,级别%level,信息%message等字段,而是自定义的业务字段。发现记录日志的info,error,debug等方法可以传入object参数:log.info(object message)。于是到网上查找它是不是象我们预想的这样,传一个自定义的业务日志对象给info方法,它自动帮我得到该业务对象的字段的值。找了半天,答案是:不行。
仔细想了下,难道别人都不这样用吗?别人是怎么传入自定义业务对象?
虽然看起来已经没有什么必要,但还是自己做出了解决方案。
下面把配置方式及传入自定义业务对象的解决方案附上。
一、log4net针对sqlserver的配置方式:
(注:如果配置写入数据库,需要将System.Data.dll拷到bin目录下。)
再写入数据库之前,首先看一下,将要写入的数据库表的结构。
表名是test_log
再看看我们自定义的消息类。
view plain copy to clipboard print ?
- public class LogContent
- {
- public string Reason{get;set;}
- public string Name { get; set; }
- }
万事具备,只欠东风了,下面就是配置文件了。
到了这里,程序还不能运行,对了,还少一个东西,那就是自定义的MyLayout呀,下面给出代码。
代码的调用
运行结果。
大功告成啦。
view plain copy to clipboard print ?
- class Program
- {
- static void Main(string[] args)
- {
- log4net.Config.XmlConfigurator.Configure();
- log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
- log.Info(new LogContent{Reason = "这是一个测试",Name = "张三"});
- Console.ReadKey();
- }
- }
view plain copy to clipboard print ?
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using log4net.Layout;
- using log4net.Layout.Pattern;
- namespace TestLogNiu
- {
- public class MyLayout : PatternLayout
- {
- public MyLayout()
- {
- this.AddConverter("property", typeof(MyMessagePatternConverter));
- }
- }
- public class MyMessagePatternConverter : PatternLayoutConverter
- {
- protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
- {
- if (Option != null)
- {
- // Write the value for the specified key
- WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));
- }
- else
- {
- // Write all the key value pairs
- WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
- }
- }
- /// <summary>
- /// 通过反射获取传入的日志对象的某个属性的值
- /// </summary>
- /// <param name="property"></param>
- /// <returns></returns>
- private object LookupProperty(string property, log4net.Core.LoggingEvent loggingEvent)
- {
- object propertyValue = string.Empty;
- PropertyInfo propertyInfo = loggingEvent.MessageObject.GetType().GetProperty(property);
- if (propertyInfo != null)
- propertyValue = propertyInfo.GetValue(loggingEvent.MessageObject, null);
- return propertyValue;
- }
- }
- }
view plain copy to clipboard print ?
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <configSections>
- <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
- </configSections>
- <log4net>
- <root>
- <level value="All" />
- <appender-ref ref="AdoNetAppender"/>
- </root>
- <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
- <bufferSize value="1" />
- <connectionType value="System.Data.SqlClient.SqlConnection,System.Data, Version=1.0.3300.0, Culture=neutral,PublicKeyToken=b77a5c561934e089" />
- <connectionString value="database=xxx;server=xxx;User ID=sa;Password=xxx" />
- <commandText value="INSERT INTO test_log(记录时间,消息等级,消息内容,用户名称) VALUES (@LogTime,@level,@Reason,@User)" />
- <parameter>
- <parameterName value="@LogTime" />
- <dbType value="DateTime" />
- <layout type="log4net.Layout.RawTimeStampLayout" />
- </parameter>
- <parameter>
- <parameterName value="@level" />
- <dbType value="String" />
- <size value="50" />
- <layout type="log4net.Layout.PatternLayout" value="%level" />
- </parameter>
- <parameter>
- <parameterName value="@Reason" />
- <dbType value="String" />
- <size value="100" />
- <layout type="TestLogNiu.MyLayout, TestLogNiu" >
- <param name="ConversionPattern" value="%property{Reason}"/>
- </layout>
- </parameter>
- <parameter>
- <parameterName value="@User" />
- <dbType value="String" />
- <size value="20" />
- <layout type="TestLogNiu.MyLayout, TestLogNiu" >
- <param name="ConversionPattern" value="%property{Name}"/>
- </layout>
- </parameter>
- </appender>
- </log4net>
- </configuration>