log4net:保存自定义参数到数据库

时间:2024-01-20 20:29:09
  1. log4net:保存日志到数据库
  2. 自定义参数
    1. 新建一个类,继承于PatternLayoutConverter
      public class CustomerPatternConverter : 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;
      }
      }
    2. 创建自定义Layout
      public class MyLayout:log4net.Layout.PatternLayout
      {
      public MyLayout()
      {
      this.AddConverter("Customer",typeof(CustomerPatternConverter));
      }
      }
    3. 创建一个类,用来保存需要保存到数据库中的数据
      public class LogContent
      { public string CustomerCol { get; set; } public string Test { get; set; }
      }
    4. 修改数据库的表结构
      alter table dbo.[log] add customerCol nvarchar(max)
      alter table dbo.[log] add Test nvarchar(max)
    5. 修改配置文档,在文档中添加如下parameter
      <parameter>
      <parameterName value="@customerCol"/>
      <dbtype value="String"/>
      <size value=""/>
      <Layout type="Tospur.Test.Log4net.MyLayout">
      <param name="ConversionPattern" value="%Customer{CustomerCol}"></param>
      </Layout>
      </parameter>
      <parameter>
      <parameterName value="@Test"/>
      <dbtype value="String"/>
      <size value=""/>
      <Layout type="Tospur.Test.Log4net.MyLayout">
      <param name="ConversionPattern" value="%Customer{Test}"></param>
      </Layout>
      </parameter>
    6. 修改配置文件中的sql语
      <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[customerCol],[Test]) 
      VALUES (@log_date, @thread, @log_level, @logger, @message,@customerCol,@Test)" />
    7. 运行代码
      static void Main(string[] args)
      {
      log4net.ILog log = log4net.LogManager.GetLogger("logdb");
      log.Info(new LogContent { CustomerCol="", Test="TEst" });
      Console.ReadKey();
      }
  3. 运行程序,查看结果log4net:保存自定义参数到数据库

http://www.cnblogs.com/MQNH/articles/5603326.html