我正在使用 Serilog 进行日志记录。对于每个日志,我想记录上下文信息,例如用户名和其他一些上下文信息。所以我用静态方法创建了包装器,如下所示
public static class MyLogger
{
public static void Error(Exception ex, string messageTemplate, params object[] propertyvalues)
{
var properties = new List<object>(propertyvalues);
if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity != null)
{
var contextInfo = new
{
UserName = HttpContext.Current.User.Identity.Name
};
messageTemplate += "{@ContextInfo}";
properties.Add(contextInfo);
}
//serilog log
Log.Error(ex, messageTemplate, properties.ToArray());
}
}
然后将错误记录为
MyLogger.Error(exception,"{@SomeMetadata}",metadata);
这是可行的,但是有没有更好的方法来包含 serilog 的上下文信息
Update1
所以我根据建议创建了一个丰富器
public class HttpContextEnricher: ILogEventEnricher
{
LogEventProperty _cachedProperty;
public const string EnvironmentUserNamePropertyName = "UserName";
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
_cachedProperty = _cachedProperty ?? propertyFactory.CreateProperty(EnvironmentUserNamePropertyName, GetUserName());
logEvent.AddPropertyIfAbsent(_cachedProperty);
}
private string GetUserName()
{
if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity != null)
{
return HttpContext.Current.User.Identity.Name;
}
return string.Empty;
}
}
但是我如何调用它?哪个With
我应该使用的方法?
Log.Logger = new LoggerConfiguration()
.Enrich.With???????
.ReadFrom.AppSettings()
.CreateLogger();
Update 2
我创建了扩展方法,然后在日志记录配置期间使用它
public static class HttpContextLoggerConfigurationExtensions
{
public static LoggerConfiguration WithUserName(
this LoggerEnrichmentConfiguration enrichmentConfiguration)
{
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
return enrichmentConfiguration.With<HttpContextEnricher>();
}
}
然后在 Application_Start 事件中的 global.asax 中配置记录器
Log.Logger = new LoggerConfiguration()
.Enrich.WithUserName()
.ReadFrom.AppSettings()
.CreateLogger();
我注意到每次我记录一些内容时,enricher 都会被调用并返回 UserName,但它不会在日志中记录 UserName。我在日志中看到了我的消息,但没有看到 UserName 属性。我在用Windows 事件日志接收器 https://github.com/serilog/serilog-sinks-eventlog
我将信息记录为
Log.Information("Some message");
和错误为
Log.Error(exception, "ErrorID={ErrorID}",someid);
我缺少什么?