Loading

log4net使用封装,无缝切换 dotnet 和 dotnetcore

log4net使用封装,无缝切换 dotnet 和 dotnetcore

Intro

自己有几个自己的小项目,有许多公用的方法/扩展/工具类等等,于是封装了一些常用的工具类/扩展方法 WeihanLi.Common,日志使用了自己比较常用的 log4net,开始默认使用的log4net进行处理日志,在1.0.12版本之前直接依赖 log4net,后来觉得这样做不太好,一是多了 log4net 这一依赖而且有点一个公共类库依赖某一个具体的日志框架有点不妥,后来决定把 log4net 给独立出来,单独迁移出来一个 WeihanLi.Common.Logging.Log4Net

本文主要介绍一下,怎么通过 WeihanLi.Common.Logging.Log4Net 来使用 log4net,让你在 .net core 应用中有着和 .net framework 一致的体验

安装

通过 Nuget 安装 WeihanLi.Common.Logging.Log4Net

使用

  1. log4net 初始化

    
    Log4NetHelper.LogInit(); // 默认使用当前目录的 log4net.config 作为配置文件
    
    Log4NetHelper.LogInit(log4netConfigFilePath); // 手动指定 log4net 配置文件路径
    
  2. 获取 logger,GetLogger

    var genericLogger = Log4NetHelper.GetLogger<ClassName>();
    
    var typeLogger = Log4NetHelper.GetLogger(typeof(Program));
    
    var logger = Log4NetHelper.GetLogger("LoggerName");
    
  3. 记录日志

    logger.Debug(msg);
    logger.Info(msg);
    logger.Info(msg, exception);
    logger.Warn(msg);
    logger.Warn(msg, exception);
    logger.Error(msg);
    logger.Error(msg, exception);
    logger.Fatal(msg);
    logger.Fatal(msg, exception);
    
  4. 配置使用 ElasticsearchAppender

    log4net 示例配置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file type="log4net.Util.PatternString" value="./Log/systemLog.%date{yyyy-MM-dd}.log" />
      <appendToFile value="true" />
      <encoding value="unicodeFFFE" />
      <rollingStyle value="Date" />
      <datePattern value="yyyyMMdd" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="100" />
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data" />
      <connectionString value="data source=.;initial catalog=WebLog;integrated security=false;persist security info=True;User ID=[***];Password=[***]" />
      <commandText value="INSERT INTO [dbo].[TestLog]([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES(@log_date, @thread, @log_level, @logger, @message, @exception)" />
      <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="@exception" />
        <dbType value="String" />
        <size value="2000" />
        <layout type="log4net.Layout.ExceptionLayout" />
      </parameter>
      <filter type="log4net.Filter.LevelRangeFilter">
        <!--<param name="LevelMin" value="DEBUG" />
        <param name="LevelMax" value="ERROR" />-->
        <param name="LevelMin" value="WARN" />
      </filter>
    </appender>
    <appender name="TraceAppender" type="log4net.Appender.TraceAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
    <appender name="AspNetTraceAppender" type="log4net.Appender.AspNetTraceAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
      <mapping>
        <level value="ERROR" />
        <foreColor value="White" />
        <backColor value="Red, HighIntensity" />
      </mapping>
      <mapping>
        <level value="DEBUG" />
        <backColor value="Green" />
      </mapping>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
      <authentication value="Basic" />
      <username value="ben121011@126.com" />
      <password value="*******" />
      <to value="w***@outlook.com" />
      <from value="ben121011@126.com" />
      <subject value="logging message test" />
      <smtpHost value="smtp.126.com" />
      <bufferSize value="512" />
      <!--  超长是否丢弃 -->
      <lossy value="true" />
      <!-- 下面的定义, 就是 日志级别 大于 ERROR 的, 才发邮件.  -->
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="ERROR" />
        <levelMax value="FATAL" />
      </filter>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%newline %date  %newline [%thread] %newline %-5level %logger  %newline - %message" />
      </layout>
    </appender>
    <appender name="ElasticSearchAppender" type="WeihanLi.Common.Logging.Log4Net.ElasticSearchAppender, WeihanLi.Common.Logging.Log4Net">
      <bufferSize value="2" />
      <ElasticSearchUrl value="http://localhost:9200" />
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="TraceAppender" />
      <appender-ref ref="ConsoleAppender" />
      <appender-ref ref="RollingLogFileAppender" />
      <!--
      <appender-ref ref="ColoredConsoleAppender" />
      <appender-ref ref="AdoNetAppender" />
      <appender-ref ref="SmtpAppender" />
      <appender-ref ref="ElasticSearchAppender" />
      -->
    </root>
  </log4net>
</configuration>

Memo

如果有什么问题或建议,欢迎提出

posted @ 2019-03-01 09:47  WeihanLi  阅读(1387)  评论(0编辑  收藏  举报