Log with log4net with loglevel parameter as parameter

Is there a way to log into log4net and use the LogLevel parameter as a 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); 
+7
source share
2 answers

According to the log4net documentation here (see 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 for log4net to define the boundary in the call stack between the logging code and the application code. If you have enabled method logging, log4net moves the call stack until the DeclaringType of the MethodInfo method on the stack is equal to the passed type (the type in the log call above). When it finds that DeclaringType, the next method in the call stack is the actual call method (application code).

You can also use overloading, which takes a LoggingEvent structure.

The documentation also says that the Log method is intended for use by shells. I don’t know whether this should be considered as an “informational” message or a strong suggestion not to use it directly.

If you want to make all your log calls using the log method, you can change the code in which you get the logger so that it is (so that you can exclude the use of the Logger property for each log call):

 private static ILogger logger = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType).Logger; logger.Log(logger.GetType(),LogLevel.Debug,"Something went wrong", ex); 
+8
source

Continuing to answer @wageoghe, I wrote 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; } 

This allows you to make such calls as:

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

or formatted messages:

 Log.Log(Level.Info, "Request took {0:0} seconds", duration.TotalSeconds); 
+6
source

All Articles