serilog push属性使用多次

时间:2019-06-21 09:41:47

标签: asp.net-core serilog

我有一个根据此博客帖子https://blog.datalust.co/smart-logging-middleware-for-asp-net-core/

实现的serilog中间件类

如果我想多次使用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 }

1 个答案:

答案 0 :(得分:1)

下面是一个示例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)) 
    { ... }