仅当设置了调试变量时,log4net才会记录调试消息

时间:2013-04-30 12:58:22

标签: c# log4net ndesk.options

我有一个控制台应用程序,它正在使用log4net设置,目前仅将信息记录到控制台输出。

我有各种log.Debug("Debug info")语句,如果我的应用程序中设置了调试标志,我只想打印到控制台。

调试变量是通过读取调用时传递给应用程序的开关来设置的。使用NDesk.Options读取参数。

我想避免在if: -

中包装每个调试语句
bool debug = false;

// read switches        
var p = new OptionSet() {
    { "d|debug", "debug mode", v => debug = v != null },
};

if (debug) {
    log.Debug("Debug info")
}

我可以在配置的<log4net><appender>部分放置什么来启用它,还是有办法覆盖log.Debug以提供逻辑?

4 个答案:

答案 0 :(得分:1)

是的,例如:

<root>
  <level value="DEBUG" />
  <appender-ref ref="LogFileAppender" />
  <appender-ref ref="AdoNetAppender" />
  <appender-ref ref="EventLogAppender" />
</root>

答案 1 :(得分:0)

您可以尝试创建自己的appender:

public class MyAppender : AppenderSkeleton    
{
    private static bool TurnDebugOn = false;
    public static SetDebugLogging(bool toSet){
        TurnDebugOn = toSet;
    }

    protected override void Append(LoggingEvent loggingEvent)
    {
        bool logEvent = true;
        LogLevel logLevel = LogLevel.Err;
        switch (loggingEvent.Level.Name)
        {
            case "DEBUG":
                logEvent = TurnDebugOn;
                logLevel = LogLevel.Debug;
                break;
            case "WARN":
            case "INFO":
                logLevel = LogLevel.Info;
                break;
            case "ERROR":
                logLevel = LogLevel.Err;
                break;
            case "FATAL":
                logLevel = LogLevel.Critical;
                break;
        }
        if(logEvent){
            LogService.Log(LogNameEnum.Exception, LogCategoryEnum.BusinessLogic, logLevel, RenderLoggingEvent(loggingEvent));
        }
    }
} 

然后在你的代码中:

MyAppender.SetDebugLogging(true);
配置文件中的

...
<appender name="AppenderToUse" type="MyAppender">
...

答案 2 :(得分:0)

如果使用代码初始化log4net,请向appender添加调试过滤器

  private static void InitFileLogging(bool logDebugEvents)
    {
        string LOG_PATTERN = "%d [%t][%logger] %-5p %m%n";

        Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
        TraceAppender tracer = new TraceAppender();
        PatternLayout patternLayout = new PatternLayout();

        patternLayout.ConversionPattern = LOG_PATTERN;
        patternLayout.ActivateOptions();
        tracer.Layout = patternLayout;


        tracer.ActivateOptions();

        hierarchy.Root.AddAppender(tracer);

        RollingFileAppender roller = new RollingFileAppender
        {
            Layout = patternLayout,
            AppendToFile = true,
            RollingStyle = RollingFileAppender.RollingMode.Size,
            MaxSizeRollBackups = 4,
            MaximumFileSize = "300KB",
            StaticLogFileName = true,
            File = @"c:\temp\textLog.txt"
        };
        if (!logDebugEvents)
        {
            log4net.Filter.LevelMatchFilter debugFilter = new log4net.Filter.LevelMatchFilter() { AcceptOnMatch = false, LevelToMatch = Level.Debug };
            roller.AddFilter(debugFilter);
        }
        roller.ActivateOptions();


        hierarchy.Root.AddAppender(roller);

       // hierarchy.Root.Level = Level.All;
        hierarchy.Configured = true;

    }

否则,如果你是usign externar配置文件,请获取appender并添加调试过滤器。

 private static void DisableDebugFileLogging()
    {
        XmlConfigurator.Configure();
        Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
        foreach (var appender in hierarchy.GetAppenders())
        {

            RollingFileAppender rolAppender = appender as RollingFileAppender; //or whatever appender you use
            if (rolAppender != null)
            {
                log4net.Filter.LevelMatchFilter debugFilter = new log4net.Filter.LevelMatchFilter() { AcceptOnMatch = false, LevelToMatch = Level.Debug };
                rolAppender.AddFilter(debugFilter);
            }
            rolAppender.ActivateOptions();
        }
    }

答案 3 :(得分:0)

我没有广泛测试它,但你应该能够通过设置存储库的阈值来达到你想要的效果:

var repository = LogManager.GetRepository();
if (repository != null)
{
    if (debug)
    {
        repository.Threshold = Level.Debug;
    }
    else
    {
        repository.Threshold = Level.Info;
    }
}