【发布时间】:2014-11-10 00:23:39
【问题描述】:
ASP.NET Web API 2.1 包含一个新的global error handling 功能。我找到了一个example,它演示了如何将异常记录到 ELMAH 中。但我使用NLog 将错误记录到数据库表中。是否可以在 NLog 中使用 Web API 全局错误处理?如果有,请举个例子。
【问题讨论】:
标签: c# asp.net asp.net-web-api error-handling nlog
ASP.NET Web API 2.1 包含一个新的global error handling 功能。我找到了一个example,它演示了如何将异常记录到 ELMAH 中。但我使用NLog 将错误记录到数据库表中。是否可以在 NLog 中使用 Web API 全局错误处理?如果有,请举个例子。
【问题讨论】:
标签: c# asp.net asp.net-web-api error-handling 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。
【讨论】:
其他可能很方便的WebApiContrib.Tracing.NLog 包,允许您使用 ITraceWriter 接口通过 NLog 输出到日志。 ITraceWriter 的一个很酷的地方是“所有跟踪都可以与导致该代码运行的单个请求相关联(请参阅this link)
【讨论】: