Serilog 的丰富器不记录属性

问题描述 投票:0回答:1

我有 ASP.NET MVC 应用程序,我使用 Serilog 进行日志记录。我已经实现了 serilog 的丰富器来记录每个日志条目的用户用户名

public class HttpContextEnricher : ILogEventEnricher
{
    LogEventProperty _cachedProperty;

    public const string EnvironmentUserNamePropertyName = "MyUserName";

    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        if (HttpContext.Current == null)
            return;
        if (HttpContext.Current.User == null)
            return;
        if (HttpContext.Current.User.Identity == null)
            return;

        _cachedProperty = _cachedProperty ?? propertyFactory.CreateProperty(EnvironmentUserNamePropertyName, HttpContext.Current.User.Identity.Name);
        logEvent.AddPropertyIfAbsent(_cachedProperty);
    }
}

扩展方法

public static class HttpContextLoggerConfigurationExtensions
{
    public static LoggerConfiguration WithUserName(
        this LoggerEnrichmentConfiguration enrichmentConfiguration)
    {
        if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
        return enrichmentConfiguration.With<HttpContextEnricher>();
    }
}

在应用程序启动时配置它

     Log.Logger = new LoggerConfiguration()
            .Enrich.WithUserName()                       
            .ReadFrom.AppSettings()
            .CreateLogger();

这是我的应用程序设置

<add key="serilog:minimum-level" value="Information" />
<add key="serilog:using:EventLog" value="Serilog.Sinks.EventLog" />
<add key="serilog:write-to:EventLog" />
<add key="serilog:write-to:EventLog.source" value="MySource" />
<add key="serilog:write-to:EventLog.manageEventSource" value="false" />

这就是我记录的方式

Log.Information("Some information messaage");

我正在使用 WindowsEvent Sink。当我执行应用程序时,我看到消息正在记录在 Windows 的事件源中,但是日志没有

MyUserName
属性。

我不确定我在这里缺少什么?

serilog
1个回答
2
投票

我必须在outputTemplate中显式设置UserName,以便它可以写入接收器。

<add key="serilog:write-to:EventLog.outputTemplate" value="[{Level}]{NewLine}{Timestamp:MM/dd/yyyy HH:mm:ss tt}{NewLine}UserName:{MyUserName}{NewLine}Message:{Message}{NewLine}{Exception}" />
© www.soinside.com 2019 - 2024. All rights reserved.