使用NLog的ASP.NET Web API 2.1中的全局异常处理?

问题描述 投票:42回答:2

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
2个回答
52
投票

它实际上非常简单,您可以手动实现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


4
投票

其他可能是方便的WebApiContrib.Tracing.NLog包,允许您使用ITraceWriter接口输出到NLog日志。关于ITraceWriter的一个很酷的事情是“所有跟踪都可以与导致该代码运行的单个请求相关联(请参阅this link

© www.soinside.com 2019 - 2024. All rights reserved.