编程语言
首页 > 编程语言> > c# – 在ASP.NET 4.6中使用Serilog进行OWIN启动

c# – 在ASP.NET 4.6中使用Serilog进行OWIN启动

作者:互联网

我正在尝试集成serilog以进行异常的全局处理,但是当我尝试将ILoggerFactory作为新参数添加到Configuration()时,应用程序无法加载,因为它无法识别OWIN Startup.cs.任何人都可以告诉我是否遗漏了什么?下面是我的Startup.cs:

using Microsoft.Extensions.Logging;
using Microsoft.Owin;
using Owin;
using Serilog;

[assembly: OwinStartupAttribute(typeof(InvoiceAutomation.WebUI.Startup))]
namespace InvoiceAutomation.WebUI
{
    public partial class Startup
    {
        public Startup()
        {
            Log.Logger = new LoggerConfiguration()
                        .MinimumLevel.Debug()
                        .WriteTo.LiterateConsole()
                        .WriteTo.RollingFile("log-{Date}.txt")
                        .CreateLogger();
        }
        public void Configuration(IAppBuilder app, ILoggerFactory loggerFactory)
        {
            ConfigureAuth(app);
            loggerFactory.AddSerilog();
        }
    }
}

解决方法:

它不会加载,因为它需要带签名的方法

public void Configuration(IAppBuilder app)

但是你不需要使用loggerFactory.AddSerilog();再创建logger(Log.Logger = new LoggerConfiguration())就足够了.

我提出中间件的全局异常处理怎么样:

public class OwinExceptionHandlerMiddleware : OwinMiddleware
{
    private readonly ILogger logger;

    public OwinExceptionHandlerMiddleware(OwinMiddleware next, ILogger logger)
        : base(next)
    {
        this.logger = logger;
    }

    public override async Task Invoke(IOwinContext context)
    {
        try
        {
            await this.Next.Invoke(context);
        }
        catch (Exception ex)
        {
            this.logger.Error(ex, $"{nameof(OwinExceptionHandlerMiddleware)} caught exception.");
            throw;
        }
    }
}

注意,您需要在Startup.cs中注册中间件:

appBuilder.Use<OwinExceptionHandlerMiddleware>(Log.Logger);

标签:c,serilog,owin-middleware
来源: https://codeday.me/bug/20190705/1390987.html