Serilog的浓缩剂不记录属性

时间:2017-02-22 16:11:28

标签: serilog

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

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属性。

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

1 个答案:

答案 0 :(得分:1)

我必须在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}" />