2

我试过这个没有成功:How do I filter on a custom level in log4net

这是我正在使用的代码:

public static class SpecialLogging
{
    public static readonly log4net.Core.Level specialLevel = new log4net.Core.Level(35000, "SPECIAL");

    public static void Special(this ILog log, string message)
    {
        log.Logger.Log(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType,
        specialLevel, message, null);
    }
}

这是我测试它:

private static void Main()
{
    //Logger
    LogManager.GetRepository().LevelMap.Add(SpecialLogging.specialLevel);
    ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    log.Special("Special");
}

最后是我的 log4net.config 文件:

<log4net>
  <appender name="RollingLogFileAppenderDebug" type="log4net.Appender.RollingFileAppender">
    <file value="./Logs/DEBUG.log" />
    <appendToFile value="false" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="3" />
    <maximumFileSize value="5GB" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />

    <filter type="log4net.Filter.LevelRangeFilter">
      <acceptOnMatch value="true" />
      <levelMin value="DEBUG" />
      <levelMax value="FATAL" />
    </filter>

    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date{G} [%thread] (%stacktrace) %5level - %message%newline" />
    </layout>
  </appender>

  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="./Logs/Special.log" />
    <appendToFile value="false" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="3" />
    <maximumFileSize value="5GB" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />

    <filter type="log4net.Filter.LevelMatchFilter">
      <acceptOnMatch value="true" />
      <levelToMatch value="SPECIAL" />
    </filter>
    <filter type="log4net.Filter.DenyAllFilter" />

    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date{G} [%thread] (%stacktrace) %5level - %message%newline" />
    </layout>
  </appender>

  <!-- Set the default logging level and add the active appenders -->
  <root>
    <level value="ALL" />
    <appender-ref ref="RollingLogFileAppender" />
    <appender-ref ref="RollingLogFileAppenderDebug" />
  </root>

</log4net>

Debug.log 文件中出现特殊消息,但 Special.log 文件为空!

4

1 回答 1

9

您从链接到的问题中错过了Olle 的答案。

首先,所有 log4net 问题的经验法则是启用内部调试

在这种情况下,如果您添加

log4net.Util.LogLog.InternalDebugging = true;

到你的主要开始,那么你可能会看到错误

log4net:ERROR XmlHierarchyConfigurator: Unknown Level Specified [SPECIAL]
log4net:WARN Unable to set property [levelToMatch] on object [log4net.Filter.LevelMatchFilter] using value [SPECIAL] (with acceptable conversion types)

所以解决方案是将此信息添加到您的 log4net 配置部分,即

<level>
  <name value="SPECIAL" />
  <value value="35000" />
</level>
于 2012-09-20T09:59:15.363 回答