2009-08-02

.Net程序中使用log4net记录日志

Views: 10132 | Add Comments

记录下这个笔记, 方便以后查阅. log4net使用了控制台输出和文件轮换输出.

  1. 新建工程
  2. 添加对log4net.dll的引用
  3. 在AssemblyInfo.cs中增加[assembly: log4net.Config.XmlConfigurator(Watch = true)]
  4. 增加应用程序配置文件App.config, 完整内容为:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <!-- Register a section handler for the log4net section -->
      <configSections>
        <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
      </configSections>
    
      <log4net>
        <appender name="A_CONSOLE" type="log4net.Appender.ConsoleAppender">
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date{HH:mm:ss,fff} [%-5level] %logger{1} - %message%newline" />
          </layout>
        </appender>
    
        <appender name="A_FILE" type="log4net.Appender.RollingFileAppender">
    	  <file value="log.txt" />
    	  <appendToFile value="true" />
    	  <rollingStyle value="Size" />
    	  <maximumFileSize value="1024KB" />
    	  <maxSizeRollBackups value="3" />
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss.fff} [%-5level] %logger{1} - %message%newline" />
          </layout>
        </appender>
    
        <!-- Set root logger level to DEBUG and its only appender to A1 -->
        <root>
          <level value="DEBUG" />
          <appender-ref ref="A_CONSOLE" />
          <appender-ref ref="A_FILE" />
        </root>
    
      </log4net>
    </configuration>
    
  5. 使用:
    log4net.ILog log = log4net.LogManager.GetLogger(
        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    log.Debug("ideawu.net");
    
  6. Related posts:

    1. Python logging 标准配置
    2. C#封装log4net
    3. SSDB 配置文件
    4. 如何解读 SSDB 的 log
    5. 使用Python POST任意的HTTP数据以及使用Cookie
Posted by ideawu at 2009-08-02 15:03:58

Leave a Comment