在log4net中以编程方式更改日志级别? [英] Changing the log level programmatically in log4net?

查看:162
本文介绍了在log4net中以编程方式更改日志级别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过编程方式在log4net中设置日志级别?我以为会有一个可以让您执行此操作的属性,但我似乎找不到一个.

我想做的是有一个可配置的选项来进入调试模式.这会导致额外的日志记录.

我正在使用一个单独的log4net配置xml文件.目前,我提出的解决方案如下:

  1. 使用dom编辑日志文件,然后调用XMLConfigurator根据文件配置日志文件.

  2. 具有两个日志配置文件,并且在更改选项时调用xml Configurator以使用适当的日志配置文件.

我倾向于2,这有什么理由不起作用吗?

解决方案

这是我以编程方式配置log4net的方式:

//declared as a class variable   
private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

 PatternLayout layout = new PatternLayout(@"%date %-5level %message%newline");
    RollingFileAppender appender = new RollingFileAppender();
    appender.Layout = layout;
    appender.File = "c:\log.txt";
    appender.AppendToFile = true;
    appender.MaximumFileSize = "1MB";
    appender.MaxSizeRollBackups = 0; //no backup files
    appender.Threshold = Level.Error;
    appender.ActivateOptions();                       
    log4net.Config.BasicConfigurator.Configure(appender);

我认为您想要的是Appender的Threshold属性,它将控制追加程序将输出的日志记录级别.

log4net 手册有很多很好的配置示例. /p>

Is there a way to set the log level in log4net programmatically? I'd assumed that there would be a property that would let you do this, but I can't seem to find one.

What I want to do is have a configurable option to enter debug mode. which would cause extra logging.

I'm using a separate log4net configuration xml file. At the moment the solutions I've come up with are as follows:

  1. Edit the log file using the dom and then call XMLConfigurator to configure the log file as per the file.

  2. Have two log configuration files, and on the option changing call xml Configurator to use the appropriate log configuration file.

I'm leaning towards 2, is there any reason this wont work?

解决方案

This is the way I'm configuring log4net programmatically:

//declared as a class variable   
private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

 PatternLayout layout = new PatternLayout(@"%date %-5level %message%newline");
    RollingFileAppender appender = new RollingFileAppender();
    appender.Layout = layout;
    appender.File = "c:\log.txt";
    appender.AppendToFile = true;
    appender.MaximumFileSize = "1MB";
    appender.MaxSizeRollBackups = 0; //no backup files
    appender.Threshold = Level.Error;
    appender.ActivateOptions();                       
    log4net.Config.BasicConfigurator.Configure(appender);

I think the Appender's Threshold property is what you looking for, it will control what levels of logging the appender will output.

The log4net manual has lots of good configuration examples.

这篇关于在log4net中以编程方式更改日志级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆