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

dem*_*emo 43 c# asp.net error-handling nlog asp.net-web-api

ASP.NET Web API 2.1包含一个新的全局错误处理功能.我发现了一个例子,演示了如何记录异常到ELMAH.但是我使用NLog将错误记录到数据库表中.是否可以使用NLog的Web API全局错误处理?如果是,请提供一个例子.

Fil*_*p W 54

它实际上非常简单,你可以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();
    }
}
Run Code Online (Sandbox Code Playgroud)

还要将它添加到配置中:

var config = new HttpConfiguration(); 

config.Services.Add(typeof(IExceptionLogger), new NLogExceptionLogger()); 
Run Code Online (Sandbox Code Playgroud)

你可以找到完整的样品溶液在这里.