2012-09-18 117 views
1

我沒有成功嘗試這樣做:How do I filter on a custom level in log4net自定義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文件爲空!

回答

5

您錯過了Olle's answer從您鏈接到的問題。

首先,所有log4net問題的經驗法則是啓用internal debugging

在這種情況下,如果添加

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> 
+0

非常感謝! –