OWIN Startup with Serilog in ASP.NET 4.6
Asked Answered
O

1

6

I'm trying to integrate serilog for global handling of exceptions, however when I try to add ILoggerFactory as new parameter to Configuration() the app doesn't load because it can't recognize the OWIN Startup.cs anymore. Can anyone tell if I'm missing something? Below is my 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();
        }
    }
}
Openfaced answered 13/7, 2017 at 9:23 Comment(2)
try to add app.Use<LoggingMiddleware>(); and remove loggerFactoryInoperable
hi @SamvelPetrosov forgot to add, I`m using ASP.NET 4.6, does that mean I have to create a separate middleware for Serilog then inject it to OWIN pipeline?Openfaced
H
1

It won't load as it expects method with signature

public void Configuration(IAppBuilder app)

But you don't need to use loggerFactory.AddSerilog(); anymore, creating logger (Log.Logger = new LoggerConfiguration()) is sufficient.

What about global handling of exceptions I came up with middleware:

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;
        }
    }
}

Note, that you need register middleware in Startup.cs:

appBuilder.Use<OwinExceptionHandlerMiddleware>(Log.Logger);
Hued answered 18/10, 2018 at 15:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.