将用户名添加到Serilog

时间:2018-07-10 09:02:59

标签: logging asp.net-core serilog

我在 program.cs

中拥有此Serilog配置
public class Program
    {
        public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
            .Build();

        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                .MinimumLevel.Override("System", LogEventLevel.Warning)
                .WriteTo.MSSqlServer(Configuration.GetConnectionString("DefaultConnection"), "dbo.Log")
                .Enrich.WithThreadId()
                .Enrich.WithProperty("Version", "1.0.0")
                .CreateLogger();
            try
            {
                BuildWebHost(args).Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }

        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseSerilog()
                .Build();
    }

现在我想将HttpContext.Current.User.Identity.Name添加到所有日志消息中。

我尝试根据文档https://github.com/serilog/serilog/wiki/Configuration-Basics#enrichers

创建新的Enrich类
class UsernameEnricher : ILogEventEnricher
    {
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory, HttpContext httpContext)
        {
            logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
                    "Username", httpContext.User.Identity.Name));
        }
    }

但是与不知道 HttpContext ILogEventEnricher 冲突。

我还尝试安装包含用户名Enricher的Nuget软件包 Serilog.Web.Classic ,但是目标框架.Net Framework和.Net Core之间存在冲突,因此我无法使用此插件。

有什么想法吗?

4 个答案:

答案 0 :(得分:9)

您可以创建一个中间件,将所需的属性放入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);
    }
}

还需要在记录器配置中添加以下内容:

.Enrich.FromLogContext()

答案 1 :(得分:5)

如果您使用的是Serilog.AspNetCore,则添加身份验证/用户属性非常容易。

    app.UseSerilogRequestLogging(options =>
    {
         options.EnrichDiagnosticContext = PushSeriLogProperties;
    });



    public void PushSeriLogProperties(IDiagnosticContext diagnosticContext, HttpContext httpContext)
    {
            diagnosticContext.Set("SomePropertyName", httpContext.User...);
    }

答案 2 :(得分:4)

@Alex Riabov建议的方法存在很多问题。

  1. 需要Dispose推送的属性
  2. 中间件中的Invoke方法是异步的,因此您不仅可以return next(),还需要await next()
  3. 请求信息由UseSerilogRequestLogging()中间件记录。如果在到达属性之前将其弹出,则该属性将为空。

要修复它们,我建议进行以下修改。

在中间件中:

public async Task Invoke(HttpContext context)
{
    using (LogContext.PushProperty("UserName", context.User.Identity.Name ?? "anonymous"))
    {
        await next(context);
    }
}

Startup.cs中:

appl.UseRouting()
    .UseAuthentication()
    .UseAuthorization()
    .UseMiddleware<SerilogUserNameMiddleware>()
    .UseSerilogRequestLogging()
    .UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapRazorPages();
        endpoints.MapHealthChecks("/health");
    });

答案 3 :(得分:2)

使用中间件的另一种方法是使用动作过滤器。

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Serilog.Context;

namespace Acme.Widgets.Infrastructure
{
    public class LogEnrichmentFilter : IActionFilter
    {
        private readonly IHttpContextAccessor httpContextAccessor;

        public LogEnrichmentFilter(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var httpUser = this.httpContextAccessor.HttpContext.User;

            if (httpUser.Identity.IsAuthenticated)
            {
                var appUser = new AppIdentity(httpUser);
                LogContext.PushProperty("Username", appUser.Username);
            }
            else
            {
                LogContext.PushProperty("Username", "-");
            }
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            // Do nothing
        }
    }
}

在您的Startup.ConfigureServices中,您需要:

  1. 确保将IHttpContextAccessor添加到IoC容器
  2. LogEnrichmentFilter添加到IoC容器中,并以请求为范围
  3. LogEnrichmentFilter注册为全局操作过滤器

Startup.cs

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<LogEnrichmentFilter>();

services.AddMvc(o =>
{
    o.Filters.Add<LogEnrichmentFilter>();
});

然后,您应该在日志上下文中拥有在MVC action invocation pipeline中运行的代码的当前用户名。我想如果您使用resource filter而不是操作过滤器,用户名将附加到更多日志条目中,因为它们在管道中运行得更早(我只是发现了这些!)