如何在 ASP.NET 中实现 OWIN Ilogger?

How to implement OWIN Ilogger in ASP.NET?

我只是想做一些简单的日志记录,并编写有关 Web 应用程序中可能发生的错误的跟踪信息。这是一些示例代码:

public class NewLogger : Ilogger
{

}

我可能缺少对接口的一些理解,所以如果我能得到一个简短的解释如何实现这个接口,这样我就可以写一个有帮助的跟踪!

我收到如下错误:

错误1'NewLogger'没有实现接口成员'Microsoft.Owin.Logging.ILogger.WriteCore(System.Diagnostics.TraceEventType, int, object, System.Exception, System.Func)'

虽然我无法找到使用 WriteCore 方法所需的值,但我已尝试实现它,我相信我需要它。

您需要在 NewLogger class 上实现 WriteCore 方法(如错误消息所述)。像这样:

public class NewLogger : ILogger
{
    public bool WriteCore(TraceEventType eventType, int eventId, object state,
        Exception exception, Func<object, Exception, string> formatter)
    {
        if (eventType == TraceEventType.Critical)
        {
            Debug.Fail("We have a critical error " + exception);
        }
        //etc for other eventtypes

        return true;
    }
}

但是,我认为您不应该针对您的情况制作自定义记录器,而应该使用现有的实现,例如 NLog 的这个实现:http://k16c.eu/2014/12/27/using-nlog-owin-logger/