使用多次serilog推送属性

Jim*_*hoe 8 serilog asp.net-core

我有一个按照这篇博客文章实现的 serilog 中间件类https://blog.datalust.co/smart-logging-middleware-for-asp-net-core/

如果我想多次使用 LogContext.PushProperty 在日志记录中推送各种信息,我只需要将以下代码放入我的 Invoke 方法中:

LogContext.PushProperty("Address", httpContext.Connection.RemoteIpAddress);
LogContext.PushProperty("Username", httpContext.User.Identity.IsAuthenticated ? httpContext.User.Identity.Name : null);
Run Code Online (Sandbox Code Playgroud)

LogContext.PushProperty 的文档仅显示添加一个属性,并表示要使用 using 块,还是我需要执行以下操作:

using (LogContext.PushProperty("Address", 
httpContext.Connection.RemoteIpAddress))
        using (LogContext.PushProperty("Username", httpContext.User.Identity.IsAuthenticated ? httpContext.User.Identity.Name : null))
    {  //rest of invoke method here }
Run Code Online (Sandbox Code Playgroud)

小智 14

您可以使用 LogContext 的 Push 方法:

ILogEventEnricher[] enrichers = 
{
    new PropertyEnricher("Address", httpContext.Connection.RemoteIpAddress),
    new PropertyEnricher("Username", httpContext.User.Identity.IsAuthenticated ? httpContext.User.Identity.Name : null),
};

using (LogContext.Push(enrichers))
{
    // your code...
}
Run Code Online (Sandbox Code Playgroud)


小智 8

这是一个示例https://github.com/serilog/serilog/wiki/Enrichment

log.Information("No contextual properties");

using (LogContext.PushProperty("A", 1))
{
    log.Information("Carries property A = 1");

    using (LogContext.PushProperty("A", 2))
    using (LogContext.PushProperty("B", 1))
    {
        log.Information("Carries A = 2 and B = 1");
    }

    log.Information("Carries property A = 1, again");
}
Run Code Online (Sandbox Code Playgroud)

只需使用多人游戏即可

    using (LogContext.PushProperty("A", 2))
    using (LogContext.PushProperty("B", 1)) 
    { ... }
Run Code Online (Sandbox Code Playgroud)