在log4net中有2个非常好的功能:
Log.Error("Message", myException);
Run Code Online (Sandbox Code Playgroud)
和
Log.ErrorFormat("Message {0}", CustomerId);
Run Code Online (Sandbox Code Playgroud)
产品日志记录在输出日志文件中非常好.异常一个很好,因为它很好地打印了堆栈跟踪和所有异常细节,而Format 1很好,因为它允许我指定导致失败的参数.是否有"两全其美"的方法,或某种方式来制作它?
Log.ErrorFormatEx("Message {0}", CustomerId, myException)
Run Code Online (Sandbox Code Playgroud)
编辑:我经历了可能的重复问题,但它们格式错误,并没有完全像这样问...我正在寻找扩展方法或现有方法
您可以创建一个扩展方法:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像使用任何其他Log4Net方法一样使用它:
Log.ErrorFormatEx("Message {0}", exception, CustomerId);
Run Code Online (Sandbox Code Playgroud)
知道这个问题已经得到解答,但只是对于可能发现此替代方案有用的其他用户。我创建了一个 ILog 接口和一个日志类来“集中”我的 log4net 方法和逻辑。我还为“Error”方法创建了多个重载。
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);
}
Run Code Online (Sandbox Code Playgroud)
日志.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);
}
}
Run Code Online (Sandbox Code Playgroud)
用法示例
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;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 1
现在可以通过字符串插值解决这个问题:
Log.Error($"Message {CustomerId}", myException);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8031 次 |
| 最近记录: |