Search code examples
c#asp.net-coreasp.net-identityserilog

Logging events from ASP.Net core identity with serilog


Maybe somebody has already answered similiar question, but I couldn't find it - if so I would be glad for link to it.

I'm using serilog with ASP.Net core to log various events, and when it comes to my services it's pretty straightforward, I just inject logger to a service and use it there, but I also would like to log events like user logged in, user logged out, user registered etc. all of these to file using serilog, but I don't even know how to make it. Asp identity uses razor pages and there is no controller for logging in. I've found that there is logger in user manager https://learn.microsoft.com/pl-pl/dotnet/api/microsoft.aspnetcore.identity.usermanager-1.logger?view=aspnetcore-2.2 but there is no description for it, and that's probably not it. Does somebody know how to use serilog with ASP.Net Core identity? I can't configure it for it.


Solution

  • I assume that you are using the default Identity UI that comes with ASP.NET Core Identity. You are right that this UI (by default) uses Razor Pages, and Razor Pages don’t use controllers.

    However, you can still inject dependencies into Razor Pages, just by adding a constructor for the PageModel:

    public class ExamplePageModel : PageModel
    {
        private readonly ILogger<ExamplePageModel> _logger;
    
        public ExamplePageModel(ILogger<ExamplePageModel> logger)
        {
            _logger = logger;
        }
    
        public async Task OnPostAsync()
        {
            _logger.LogInformation("Doing something");
            // …
        }
    }
    

    Of course, this means that you will now have to adjust the default Identity UI quite a bit.