user230910 user230910 - 1 month ago 19
C# Question

Log4Net how to use both the ErrorFormat and the Error at the same time

In log4net there are 2 very nice functions:

Log.Error("Message", myException);


Log.ErrorFormat("Message {0}", CustomerId);

The produce log records in the output log file very nicely. The exception one is nice because it prints a stack trace and all the exception details nicely, and the Format one is nice because it allows me to specifiy the parameters that caused the failure. Is there a "best of both worlds" method, or some way to make it?

Log.ErrorFormatEx("Message {0}", CustomerId, myException)

Edit: I went through the possible duplicate questions, but they are badly formatted and don't ask it exactly like this.. I was looking for an extension method or existing method


You could create an extension method:

namespace log4net.Core
    public class Log4NetExtensions 
         public static void ErrorFormatEx(this ILog logger, string format, Exception exception, params object[] args) 
               logger.Error(string.Format(format, args), exception);

Then you can use it just like you would use any other Log4Net method:

Log.ErrorFormatEx("Message {0}", exception, CustomerId);