LogLevel disabled, log anyway

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

LogLevel disabled, log anyway

z4711
each log event is made on a certain level of your choice...
some events we want to be logged even if the prefered level has been disabled

    public static class NLogUtils
    {
        public static List<LogLevel> LogLevelOrder = new List<LogLevel> 
            { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal };

        public static LogLevel FirstEnabledLogLevel(Logger logger, LogLevel startWith, bool allowWrap = true)
        {
            foreach (LogLevel l in LogLevelOrder)
                if (l >= startWith && logger.IsEnabled(l))
                    return l;
            LogLevel res = null;
            if (allowWrap)
                foreach (LogLevel l in LogLevelOrder)
                    if (l < startWith && logger.IsEnabled(l))
                        res = l;
            return res;
        }
    }

use it like this:

// with preference as INFO, if INFO actually is disabled try WARN, then ERROR, then FATAL,  
// finally try DEBUG and TRACE (if allowWrap)

logger.Log(NLogUtils.FirstEnabledLogLevel(logger, LogLevel.Info) ?? LogLevel.Info,
                                           "this event goes to log file under nearly all circumstances");

// if no one level is enabled (FirstEnabledLogLevel returns null), we log as INFO but the event is lost


may be someone knows a better, easier way (i didn't find a public LogLevel enumerator in NLOG)
Reply | Threaded
Open this post in threaded view
|

Re: LogLevel disabled, log anyway

z4711
There are not many situations where this can be usefull...

It's used in web app with remote admin capabilities, which allows enabling and disabling LogLevels at runtime.
Finally it's only used to log the loglevel state changes themself (enabling or disabling log levels are normally logged as INFO).