简要的Log4Net 应用配置

只是记录不描述。 详细看官方网站

Winform

 <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
Web
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
 
 <log4net>

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

      <file value="log/Log.txt" />

      <appendToFile value="true" />

      <rollingStyle value="Date" />

      <datePattern value="yyyyMMdd&quot;.txt&quot;" />

      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />



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

        <conversionPattern value="%date [%thread] %-5level %logger - %message%n" />

      </layout>

    </appender>

    <root>

      <level value="INFO" />

      <appender-ref ref="FileAppender" />

    </root>

  </log4net>
 
在Namespace的上方写一个,那个Dll 需要就要往那个dll加。

Winform or Dll 需要加入下面一项,一般加入Assembly.cs

[assembly: XmlConfigurator(Watch = true)]

namespace namespace

{
}
 
LOG Level
OFF>FATAL > ERROR > WARN > INFO > DEBUG > ALL
 
不锁死文件:<lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> 
 

变量集合

%newline%

 

Filter

appender里面的filter,我一般用于分离输出的,如Error Fatal一个文件,INFO WARN一个文件之类的。

下面这个是只输出 WARN 和 INFO信息。 最后一个的DenyAllFilter 是必须的。Value不区分大小写,很有Microsoft的风格。

<filter type="log4net.Filter.LevelMatchFilter">
       <param name="LevelToMatch" value="WARN" />
</filter>

<filter type="log4net.Filter.LevelMatchFilter"> 
      <param name="LevelToMatch" value="INFO" /> 
</filter>

<filter type="log4net.Filter.DenyAllFilter" />


通过编程方式动态改变Level

  private void SetLogingLevel(string strLogLevel)

        {

            string strChecker = "WARN_INFO_DEBUG_ERROR_FATAL";

            if (String.IsNullOrEmpty(strLogLevel) == true || strChecker.Contains(strLogLevel) == false)

                throw new Exception(" The strLogLevel should be set to WARN , INFO , DEBUG ,");



            log4net.Repository.ILoggerRepository[] repositories = log4net.LogManager.GetAllRepositories();

            //Configure all loggers to be at the debug level. 

            foreach (log4net.Repository.ILoggerRepository repository in repositories)

            {

                repository.Threshold = repository.LevelMap[strLogLevel];

                log4net.Repository.Hierarchy.Hierarchy hier = (log4net.Repository.Hierarchy.Hierarchy)repository;

                log4net.Core.ILogger[] loggers = hier.GetCurrentLoggers();

                foreach (log4net.Core.ILogger logger in loggers)

                {

                    ((log4net.Repository.Hierarchy.Logger)logger).Level = hier.LevelMap[strLogLevel];

                }

            }

            //Configure the root logger. 

            log4net.Repository.Hierarchy.Hierarchy h = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository();

            log4net.Repository.Hierarchy.Logger rootLogger = h.Root;

            rootLogger.Level = h.LevelMap[strLogLevel];

        }

你可能感兴趣的:(log)