ASP.NET Web API 2.1 包括一个新的 global error handling能力。我找到了一个 example这演示了如何将异常记录到 ELMAH 中。但是我用NLog将错误记录到数据库表中。是否可以将 Web API 全局错误处理与 NLog 一起使用?如果是,请提供示例。
最佳答案
其实很简单,要么自己实现IExceptionLogger
,要么继承基类ExceptionLogger
。
public class NLogExceptionLogger : ExceptionLogger
{
private static readonly Logger Nlog = LogManager.GetCurrentClassLogger();
public override void Log(ExceptionLoggerContext context)
{
Nlog.LogException(LogLevel.Error, RequestToString(context.Request), context.Exception);
}
private static string RequestToString(HttpRequestMessage request)
{
var message = new StringBuilder();
if (request.Method != null)
message.Append(request.Method);
if (request.RequestUri != null)
message.Append(" ").Append(request.RequestUri);
return message.ToString();
}
}
同时将其添加到配置中:
var config = new HttpConfiguration();
config.Services.Add(typeof(IExceptionLogger), new NLogExceptionLogger());
您可以找到完整的示例解决方案 here .
关于c# - 使用 NLog 在 ASP.NET Web API 2.1 中进行全局异常处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25865610/