Saturday, February 04, 2012
 
The best way to analyze your logs! Minimize
 Log4Net Mail archive   

The Log4Net mailing list is a great source of information about using log4Net, in this forum we collect all the messages in the log4net user list and some selected threads from the developer list.

Subject: Change the log level programmatically?
Prev Next
You are not authorized to post a reply.

Author Messages
Eric Rose (erose)

01/31/2009 4:21 AM  

 

Hopefully this is an easy question which has already been asked (and answered) before.

I searched online, but could not find a reasonable answer…

 

Is there a way to change the default log level of a logger via C# program control?

 

I don’t need the setting to persist, so I don’t want to have to change the XML config file and re-read it.

 

In my C# code, I have a ILog variable that we use for all logging, defined as follows:

 

private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

 

I’d like to be able to somehow be able to use that ‘log’ variable, and set it’s log level (INFO, WARN, ERROR, OFF, ALL, etc) to whatever I want in the code.

 

 

Any help or pointers to useful examples would be appreciated!

 

Thanks,

-esr

 

 

Eric Rose (erose)

02/11/2009 3:37 PM  

Hi,

 

I sent this question a couple of weeks ago, but haven’t heard any feedback from anyone…

Could someone offer some suggestions here, or let me know that this can’t be done?!

 

Thanks,

 

-esr

 

Nick Durcholz

02/11/2009 4:01 PM  

There isn't a clean way to do this with the interfaces provided.  If you really MUST have this, you could probably hack something up, but it would require breaking some of the abstractions that the framework tries to enforce.  You could also try loading the config xml into memory, modifying it using the dom, and then reconfiguring the entire heirarchy using log4net.Config.XmlConfigurator.Configure(ILoggerRepository repository, XmlElement element).  I've never tried this, so can't really say what pitfalls and 'gotchas' come along with doing that.

Why do you need to change the level of a logger at runtime in the first place?  There may be a better way to accomplish the task at hand without doing that.

Eric Rose (erose)

02/11/2009 4:11 PM  

Thanks Nick,

I'm not going to hack the log4net code, so that's not really an option.
I'm asking about this, because one of the developers had asked if there
was a way to do this.

But, it sounds like it's not really possible, unless we want to modify
the config file...

So, thanks for the information!

-esr

Francine Taylor

02/11/2009 7:12 PM  

How about something like this?

private void ChangeLogLevel(string pLoggerName, Level pLogLevel) {
    Logger ll = SafeSearchForLogger(pLoggerName);
    if (ll != null) {
       ll.Level = pLogLevel;
    }
}

// this method looks for a named logger.  If it doesn't already exist,
null
// is returned
public static Logger SafeSearchForLogger(string loggerName) {
    foreach (ILogger a in ThisHierarchy().GetCurrentLoggers()) {
        if (a.Name.Equals(loggerName)) {
            return (Logger)a;
        }
    }
    return null;
}


-----Original Message-----
From: Eric Rose (erose) [mailto:erose@cisco.com]
Sent: Wednesday, February 11, 2009 7:11 AM
To: Log4NET User
Cc: Eric Rose (erose)
Subject: RE: Change the log level programmatically?

Thanks Nick,

I'm not going to hack the log4net code, so that's not really an option.
I'm asking about this, because one of the developers had asked if there
was a way to do this.

But, it sounds like it's not really possible, unless we want to modify
the config file...

So, thanks for the information!

-esr

Ron Grabowski

02/11/2009 7:52 PM  

// untested
public class HierarchyLoggerLevelScope : IDisposable
{
    private readonly Level originalLevel;
    private readonly Logger logger;

    public HierarchyLoggerLevelScope(ILog log, Level level)
    {
        logger = log.Logger as Logger;

        if (logger != null)
        {
            originalLevel = logger.Level;
            logger.Level = level;
        }
    }

    public void Dispose()
    {
        if (logger != null)
        {
            logger.Level = originalLevel;
        }
    }
}


Eric Rose (erose)

02/11/2009 9:40 PM  

Thanks to everyone for their suggestions…

No single suggestion worked completely for me, but there were nuggets of information that were quite helpful!

I just spent a while figuring out what works for me, and this is the result…

 

We have a static utility class as follows, and I was able to add these ‘SetLevel<Level>’ methods to modify the one logging object we setup, to change the log levels on the fly.

There is still a log4net.conf file which defines all the usual things (log file location, appending rules, etc)

 

Here’s the code:

 

using log4net;

using log4net.Appender;

using log4net.Core;

using log4net.Repository.Hierarchy;

 

    public static class LogUtility

    {

        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private static readonly Logger logger = log.Logger as Logger;

 

        public static log4net.ILog GetLog()

        {

            return (log);

        }

 

        private static void SetLevel(Level level)

        {

            if (logger != null)

            {

                logger.Level = level;

            }

        }

        public static void SetLevelDebug()

        {

            SetLevel(Level.Debug);

        }

        public static void SetLevelInfo()

        {

            SetLevel(Level.Info);

        }

        public static void SetLevelWarn()

        {

            SetLevel(Level.Warn);

        }

        public static void SetLevelError()

        {

            SetLevel(Level.Error);

        }

        public static void SetLevelFatal()

        {

            SetLevel(Level.Fatal);

        }

        public static void SetLevelOff()

        {

            SetLevel(Level.Off);

        }

        public static void SetLevelAll()

        {

            SetLevel(Level.All);

        }

    }

 

 

Here’s a code fragment that tests this:

                  LogUtility.SetLevelOff();

            LogUtility.GetLog().Debug("After SetLevelOff() debug");

            LogUtility.GetLog().Warn("After SetLevelOff() warn");

            LogUtility.GetLog().Fatal("After SetLevelOff() fatal");

 

            LogUtility.SetLevelInfo();

            LogUtility.GetLog().Debug("After SetLevelInfo() debug");

            LogUtility.GetLog().Warn("After SetLevelInfo() warn");

            LogUtility.GetLog().Fatal("After SetLevelInfo() fatal");

 

            LogUtility.SetLevelError();

            LogUtility.GetLog().Debug("After SetLevelError() debug");

            LogUtility.GetLog().Warn("After SetLevelError() warn");

            LogUtility.GetLog().Fatal("After SetLevelError() fatal");

 

            LogUtility.SetLevelWarn();

            LogUtility.GetLog().Debug("After SetLevelWarn() debug");

            LogUtility.GetLog().Warn("After SetLevelWarn() warn");

            LogUtility.GetLog().Fatal("After SetLevelWarn() fatal");

           

            LogUtility.SetLevelAll();

            LogUtility.GetLog().Debug("After SetLevelALL() debug");

            LogUtility.GetLog().Warn("After SetLevelALL() warn");

            LogUtility.GetLog().Fatal("After SetLevelALL() fatal");

 

 

And, this is what the log file output looks like:

3: erose-xp5: Feb 11 2009 15:11:07.803 -05:00: %testLog-WARN-After SetLevelInfo() warn

4: erose-xp5: Feb 11 2009 15:11:07.803 -05:00: %testLog-FATAL-After SetLevelInfo() fatal

5: erose-xp5: Feb 11 2009 15:11:07.803 -05:00: %testLog-FATAL-After SetLevelError() fatal

6: erose-xp5: Feb 11 2009 15:11:07.803 -05:00: %testLog-WARN-After SetLevelWarn() warn

7: erose-xp5: Feb 11 2009 15:11:07.803 -05:00: %testLog-FATAL-After SetLevelWarn() fatal

8: erose-xp5: Feb 11 2009 15:11:07.803 -05:00: %testLog-DEBUG-After SetLevelALL() debug

9: erose-xp5: Feb 11 2009 15:11:07.803 -05:00: %testLog-WARN-After SetLevelALL() warn

10: erose-xp5: Feb 11 2009 15:11:07.803 -05:00: %testLog-FATAL-After SetLevelALL() fatal

 

 

So, it is possible, and does work!

 

Thanks again, everyone…!

 

-esr

 

 

You are not authorized to post a reply.
Forums > Log4Net > Log4Net Mail archive > Change the log level programmatically?



ActiveForums 3.7

 

 

 

 

 

 

 

 

Log4Net Dashboard

Log analysis and monitoring made easy!

Log4Net Dashboard is a log viewer that can read log statements from a variety of logging output targets.

You can download a free developer version.

  

Check it out!

On the demonstration site you can try it  with live data.demo.l4ndash.com - Try Log4Net Dashboard with live data

The mail archive is a copy of all the mail sent to the mail address: log4net-user@logging.apache.org, organized as a forum.

If you would like to participate in the mail list, send a mail to log4net-user-subscribe@logging.apache.org.

More information about the mailing list is available on: http://logging.apache.org/log4net/support.html

 

A complete topic list is available and can be viewed here (warning, it takes some time to load)

 

Copyright 2005-2008 by FaktNet AS Terms Of Use Privacy Statement