首页 > 代码库 > log4net的使用

log4net的使用

1.下载log4net.dll

2.将组件添加引用到项目中

3.项目里新建一个配置文件Log4Net.config,删除自动生成的代码,Copy下列代码到该文件.

 

<?xml version="1.0"?>

<configuration>

<startup>

  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>

</startup>

  <span style="color: rgb(102, 102, 204);"><appSettings>

    <add key="log4net.Internal.Debug" value="http://www.mamicode.com/true"/>

  </appSettings>

  <log4net>

    <!-- A1 is set to be a ConsoleAppender -->

    <appender name="A1" type="log4net.Appender.FileAppender">

      <file value="http://www.mamicode.com/logfile.txt" />

      <appendToFile value="http://www.mamicode.com/false" />

 

      <!-- A1 uses PatternLayout -->

      <layout type="log4net.Layout.PatternLayout">

        <conversionPattern value="http://www.mamicode.com/%-4timestamp [%thread] %-5level %logger %ndc - %message%newline" />

      </layout>

    </appender>

 

 

    <!-- Set root logger level to DEBUG and its only appender to A1 -->

    <root>

      <level value="http://www.mamicode.com/DEBUG" />

      <appender-ref ref="A1" />

    </root>

  </log4net>

  <configSections>

    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>

  </configSections></span>

</configuration>

 

4.在程序类里面加入(注意是在namespace上面加)

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); 

5.并在执行程序里面加

log.Debug("hello");

运行后,在bin目录里面会生成logfile.txt

 

也可以自定义一个静态类

         

namespace Attendance

{

statuc class Log4net.ILog staticlog=log4net.LogManger.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

public static log4net.ILog log

{

get

{

return staticlog;

}

set

{

}

}

}

              

在方法中调用       staticlog.Warn(“”);  staticlog.Error(“”);  staticlog.Info(“”);

Staticlog.Debug(“”);  staticlog.Off(“”);  staticlog.Fatal(“”);

  1. <!-- 日志级别:
  2. 级别 允许的方法 Boolean属性 优先级别
  3. OFF Highest
  4. FATAL void Fatal(...); bool IsFatalEnabled;
  5. RROR void Error(...); bool IsErrorEnabled;
  6. WARN void Warn(...); bool IsWarnEnabled;
  7. INFO void Info(...); bool IsInfoEnabled;
  8. DEBUG void Debug(...); bool IsDebugEnabled;
  9. ALL Lowest

10. -->