Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the log level programmatically in log4net?

Tags:

c#

log4net

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?

like image 629
Omar Kooheji Avatar asked Mar 16 '09 14:03

Omar Kooheji


2 Answers

You can programmatically change the Logging level of a log4net logger, but it's not obvious how to do so. I have some code that does this. Given this Logger:

private readonly log4net.ILog mylogger;

You have to do the following fancy footwork to set it to Debug:

((log4net.Repository.Hierarchy.Logger)mylogger.Logger).Level = log4net.Core.Level.Debug;
like image 136
Eddie Avatar answered Sep 19 '22 12:09

Eddie


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.

like image 41
Millhouse Avatar answered Sep 19 '22 12:09

Millhouse