Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log with log4net with the loglevel as parameter

Tags:

c#

log4net

Is there a way to log with log4net and use the LogLevel as parameter?

That is, instead of writing

Log.Debug("Something went wrong");

I would like to write something like this:

Log("Something went wrong", LogLevel.Debug);
like image 322
olif Avatar asked Sep 24 '12 15:09

olif


2 Answers

According to the log4net documentation here (look under log4net.Core.ILogger), you can use the Log method on the ILogger interface.

private static ILog logger = 
    LogManager.GetLogger(
    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

logger.Logger.Log(logger.GetType(),LogLevel.Debug,"Something went wrong", ex);

The Type parameter is used by for log4net to determine the boundary in the call stack between logging code and application code. If you have method name logging enabled, log4net navigates up the call stack until the DeclaringType of the MethodInfo on the stack is equal to the passed in Type (the Type in the Log call above). When it finds that DeclaringType, the next method in the call stack is the actual calling method (application code).

You can also use the overload that takes a LoggingEvent structure.

The documentation also says that the Log method is intended to be used by wrappers. I don't know if that should be regarded as an "informational" message or a strong suggestion to not use it directly.

If you want to make all of your logging calls via the Log method, you can change the code where you get the logger to be like this (so you can eliminate using the Logger property for every Log call):

private static ILogger logger = 
    LogManager.GetLogger(
    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType).Logger;

logger.Log(logger.GetType(),LogLevel.Debug,"Something went wrong", ex);
like image 57
wageoghe Avatar answered Nov 12 '22 19:11

wageoghe


Extending on @wageoghe's answer, I've written the following extension methods:

public static bool Log(this ILog log, Level level, string message, Exception exception = null)
{
    var logger = log.Logger;
    if (logger.IsEnabledFor(level))
    {
        logger.Log(logger.GetType(), level, message, exception);
        return true;
    }

    return false;
}

public static bool LogFormat(this ILog log, Level level, string messageFormat, params object[] messageArguments)
{
    var logger = log.Logger;
    if (logger.IsEnabledFor(level))
    {
        var message = string.Format(messageFormat, messageArguments);
        logger.Log(logger.GetType(), level, message, exception: null);

        return true;
    }

    return false;
}       

These allow you to make calls such as:

Log.Log(Level.Debug, "Something went wrong", myException);

or formatted messages:

Log.Log(Level.Info, "Request took {0:0} seconds", duration.TotalSeconds);
like image 26
antmeehan Avatar answered Nov 12 '22 21:11

antmeehan