.net 使用Log4net 输出日志到数据库

原创
2016/05/09 14:40
阅读数 1K

写入数据库中第一步需要修改配置文件:

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

  <log4net>
    <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
      <!--缓冲区数据大小,当日志到达多条时候才插入数据库-->
      <bufferSize value="0" />
      <!--数据库连接类型-->
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <!--数据连接字符串-->
      <connectionString value="Data Source=192.168.0.125;Initial Catalog=Logs;User ID=sa;Password=123;" />
      <!--插入数据库的sql语句-->
      <commandText value="INSERT INTO log([dtDate],[sThread],[sLevel],[sLogger],[sException],[sMessage],[sUserName]) VALUES (@log_date, @thread, @log_level, @logger, @exception, @message,@userName)" />
      <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="%thread" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@log_level" />
        <dbType value="String" />
        <size value="200" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%level" />
        </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="@exception" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.ExceptionLayout" />
      </parameter>
      <!--message 自定义消息。需要指定类型-->
      <parameter>
        <parameterName value="@message" />
        <dbType value="String" />
        <size value="3000" />
        <layout type="Log.CustomPatternLayout,Log">
          <conversionPattern value="%property{Message}" />
        </layout>
      </parameter>
      <!--userName 自定义消息。需要指定类型-->
      <parameter>
        <parameterName value="@userName" />
        <dbType value="String" />
        <size value="50" />
        <layout type="Log.CustomPatternLayout,Log">
          <conversionPattern value="%property{UserName}"/>
        </layout>
      </parameter>

    </appender>
    <root>
      <!-- 如果不启用相应的日志记录,可以通过这种方式注释掉  -->
      <!--<appender-ref ref="LogFileAppender" />-->
      <!--以数据库方式输出-->
      <appender-ref ref="ADONetAppender" />
    </root>
  </log4net>
</configuration>

对于自定义消息类型

<layout type="Log.CustomPatternLayout,Log">

需要定义:

  public class CustomPatternLayout : PatternLayout {

        public CustomPatternLayout() {

            // 添加自定义属性转换
            this.AddConverter("property", typeof(CustomPatternLayoutConverter));
        }
    }

CustomPatternLayoutConverter:

 public class CustomPatternLayoutConverter : PatternLayoutConverter {

        /// <summary>
        /// 重写转换方法
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="loggingEvent"></param>
        protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent) {
            if (null != this.Option) {
                WriteObject(writer, loggingEvent.Repository, LookupProperty(this.Option, loggingEvent));
            } else {
                WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
            }
        }

        private object LookupProperty(string property, LoggingEvent loggingEvent) {
            object propertyValue = string.Empty;
            PropertyInfo info = loggingEvent.MessageObject.GetType().GetProperty(property);
            if (null != info)
                propertyValue = info.GetValue(loggingEvent.MessageObject, null);
            return propertyValue;
        }
    }

数据库:

create table Log(
    [nId] [bigint] IDENTITY(1,1) NOT NULL,   
    [dtDate] [datetime] NOT NULL,   
    [sThread] [nvarchar](100) NOT NULL,   
    [sLevel] [nvarchar](200) NOT NULL,   
    [sLogger] [nvarchar](500) NOT NULL,   
    [sMessage] [nvarchar](3000) NULL,
    [sUserName] [nvarchar] (50) NULL,
    [sException] [nvarchar](4000) NULL 
)


test:

   static void Main(string[] args) {
            ILog log = null;
            try {
                log4net.Config.XmlConfigurator.Configure(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));
                log = LogManager.GetLogger("test");

                log.Info(new CustomLogMessage() {
                    UserName = "Mr.k",
                    Message = "custom msg",
                });
                throw new Exception("异常啦!!");
            } catch (Exception error) {
                Console.WriteLine(error);
                log.Error(new CustomLogMessage() {
                    UserName = "Mr.k",
                    Message = "err msg",
                }, error);
            }
            Console.ReadKey();
        }


查看数据库结果:



展开阅读全文
打赏
2
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
2
分享
返回顶部
顶部