多次使用 serilog push 属性

serilog push property using multiple times

我有一个 serilog 中间件 class 按照这个博客实现 post 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);

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 }

这是一个例子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");
}

只需使用

进行多人游戏
    using (LogContext.PushProperty("A", 2))
    using (LogContext.PushProperty("B", 1)) 
    { ... }

您可以对 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...
}