Log4Net how to use both the ErrorFormat and the Error at the same time
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);
Know this has been answered already, but just for other users who might find this alternative useful. I created a ILog Interface and a Log Class to "centralize" my log4net methods and logic. Also I created multiple overloads for the "Error" method.
ILog.cs
public interface ILog
{
void Error(Exception exception);
void Error(string customMessage, Exception exception);
void Error(string format, Exception exception, params object[] args);
void Warn(Exception exception);
void Info(string message);
}
Log.cs
public class Log : ILog
{
public void Error(Exception exception)
{
log4net.ILog logger = log4net.LogManager.GetLogger(exception.TargetSite.DeclaringType);
logger.Error(exception.GetBaseException().Message, exception);
}
public void Error(string customMessage, Exception exception)
{
log4net.ILog logger = log4net.LogManager.GetLogger(exception.TargetSite.DeclaringType);
logger.Error(customMessage, exception);
}
public void Error(string format, Exception exception, params object[] args)
{
log4net.ILog logger = log4net.LogManager.GetLogger(exception.TargetSite.DeclaringType);
logger.Error(string.Format(format, args), exception);
}
public void Warn(Exception exception)
{
log4net.ILog logger = log4net.LogManager.GetLogger(exception.TargetSite.DeclaringType);
logger.Warn(exception.GetBaseException().Message, exception);
}
public void Info(string message)
{
log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
logger.Info(message);
}
}
Example usage
public MyClass DeserializeJsonFile(string path)
{
try
{
using (StreamReader r = new StreamReader(path))
{
string json = r.ReadToEnd();
return JsonConvert.DeserializeObject<MyClass>(json);
}
}
catch (Exception ex)
{
this.log.Error("Error deserializing jsonfile. FilePath: {0}", ex, path);
return null;
}
}
This is now solved with string interpolation:
Log.Error($"Message {CustomerId}", myException);