Reputation: 34119
I have ASP.NET MVC application and im using Serilog for logging purpose. I have implemented serilog's enricher to log user's username for every log entry
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);
}
}
Extension Method
public static class HttpContextLoggerConfigurationExtensions
{
public static LoggerConfiguration WithUserName(
this LoggerEnrichmentConfiguration enrichmentConfiguration)
{
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
return enrichmentConfiguration.With<HttpContextEnricher>();
}
}
Configured it at application start
Log.Logger = new LoggerConfiguration()
.Enrich.WithUserName()
.ReadFrom.AppSettings()
.CreateLogger();
Here is my app settings
<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" />
This is how i am logging
Log.Information("Some information messaage");
I am using WindowsEvent Sink. When i execute the application i see the message is getting logged in the windows's event source, however the log does not have MyUserName
property.
I am not sure what i am missing here?
Upvotes: 1
Views: 3207
Reputation: 34119
I had to explicitly set UserName in outputTemplate so that it can write to sink.
<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}" />
Upvotes: 2