大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > C#技巧 > log4net修改数据库连接字符串和写自定义信息

log4net修改数据库连接字符串和写自定义信息

关键词:log4net  阅读(1915) 赞(11)

[摘要]本文是对log4net修改数据库连接字符串和写自定义信息的讲解,对学习C#编程技术有所帮助,与大家分享。

最近项目需要用log4net来写日志,因为整个平台式在sharepoint上,我们需要记录具体是哪个子站点发生的日志,因此需要再原来的log表里面添加一个自定义信息列。由于平台的安全性要求,我们需要对连接字符串加密。连接字符串的信息是在AdoNetAppender读取的,所以我们要扩展该类。而自定义消息我们需要扩展PatternLayout类。其实有关log4net的介绍网上已经很多了,如log4net.dll使用

具体的代码如下:

  #region Log helper
    public class LogMessage
    {
        public string CustomMessage { get; set; }

        public string Message { get; set; }

        public override string ToString()
        {
            return Message;
        }
    }
    internal class CustomMessageConverter : PatternLayoutConverter
    {

        protected override void Convert(TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
        {
            var logMessage = loggingEvent.MessageObject as LogMessage;

            if (logMessage != null)
            {
                writer.Write(logMessage.CustomMessage);

            }
        }
    }
    internal class CustomLayout : PatternLayout
    {

        public CustomLayout()
        {
            this.AddConverter("CustomMessage", typeof(CustomMessageConverter));
        }
    }

    public class CustAdoNetAppender : AdoNetAppender
    {
        string _connectiongStr = string.Empty;
        public new string ConnectionString
        {
            set
            {
                _connectiongStr = value;
                base.ConnectionString = _connectiongStr;
            }
            get
            {
                return base.ConnectionString;
            }
        }
    }
    #endregion

配置代码

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
  </configSections>

  <log4net>
    <logger name="MyLogger">
      <level value="ALL"></level>
      <appender-ref ref="ADONetAppender"></appender-ref>
    </logger>
    <!--记录日志到数据库-->
    <appender name="ADONetAppender" type="ConsoleApp.CustAdoNetAppender">
      <bufferSize value="100" />
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <connectionString value="data source=.;initial catalog=test;integrated security=false;persist security info=True;User ID=sa;Password=xxx" />
        <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[CustomMessage]) VALUES (@log_date, @thread, @log_level, @logger, @message,@customMessage)" />
      <parameter>
        <parameterName value="@log_date" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.RawTimeStampLayout" />
      </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="@customMessage" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="ConsoleApp.CustomLayout">
          <conversionPattern value="%CustomMessage" />
        </layout>
      </parameter>
    </appender>
  </log4net>
</configuration>

SQL脚本如下:

     CREATE TABLE [dbo].[Log] ( 
       [ID] [int] IDENTITY (1, 1) NOT NULL ,
       [Date] [datetime] NOT NULL ,
       [Thread] [varchar] (255) NOT NULL ,
       [Level] [varchar] (20) NOT NULL ,
       [Logger] [varchar] (255) NOT NULL ,
       [Message] [varchar] (4000) NOT NULL ,
       [CustomMessage] VARCHAR(max) NULL
     ) ON [PRIMARY]

在AssemblyInfo.cs文件中添加一句

[assembly: log4net.Config.DOMConfigurator(ConfigFile = "Log4Net.xml", Watch = true)]

调用代码:

ILog log = LogManager.GetLogger("MyLogger");
log.Info(new LogMessage { Message = "message", CustomMessage = "cust" });

运行结果:



相关评论