C#在window服务配置Log4Net.dll

一、使用背景:

  C#window服务下添加一个日志记录程序集(Log4Net.dll)

二、添加和使用步骤如下:

下载并引入Log4Net.dll程序集到项目中

  下载地址:http://logging.apache.org/log4net/download_log4net.cgi

在App.Config中添加对应的节点

<!--重点configsections必须是第一个节点1og4net配置-->
<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>

 在App.Config中添加Log4Net.dll初始化信息(主要一些按照什么格式存储,存储位置的配置)

  <log4net>
  <!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
  <!-- Set root logger level to ERROR and its appenders -->
  <root>
  <level value="ALL" />
  <appender-ref ref="SysAppender" />
  </root>
  <!-- Print only messages of level DEBUG or above in the packages -->
  <logger name="WebLogger">
  <level value="DEBUG" />
  </logger>
  <appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net">
  <!--日志文件夹名称-->
  <param name="File" value="ProJectsLogs/" />
  <param name="AppendToFile" value="true" />
  <param name="RollingStyle" value="Date" />
  <param name="DatePattern" value="&quot;Logs_&quot;yyyyMMdd&quot;.txt&quot;" />
  <param name="StaticLogFileName" value="false" />
  <layout type="log4net.Layout.PatternLayout,log4net">
  <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
  </layout>
  </appender>
  <appender name="consoleApp" type="log4net.Appender.ConsoleAppender,log4net">
  <layout type="log4net.Layout.PatternLayout,log4net">
  <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
  </layout>
  </appender>
  </log4net>

 在AssemblyInfo.cs:配置文件中读取配置Log4net.dll

[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]

 使用Log4Net.Dll记录日志

//首先实例化Log4net
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

//使用记录信息
log.Debug("Debug", new Exception("Debug"));
log.Info("Info", new Exception("Info"));
log.Warn("Warn", new Exception("Warn"));
log.Error("Error", new Exception("Error"));
log.Fatal("Fatal", new Exception("Fatal"));

 

posted @ 2019-01-05 03:04  追逐时光者  阅读(2365)  评论(1编辑  收藏  举报