Add Username into Serilog

You can create a middleware to put required property to LogContext.

public class LogUserNameMiddleware
{
    private readonly RequestDelegate next;

    public LogUserNameMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public Task Invoke(HttpContext context)
    {
        LogContext.PushProperty("UserName", context.User.Identity.Name);

        return next(context);
    }
}

Also you need to add the following to your logger configuration:

.Enrich.FromLogContext()

In Startup add the middleware LogUserNameMiddleware, and also note that the middleware should be added after UserAuthentication, in order to have context.User.Identity initialized

e.g.

    app.UseAuthentication();     

    app.UseMiddleware<LogUserNameMiddleware>();

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)