有没有像 HTTPContextEnricher 这样的东西可以与 Servicestack 和 Serilog 一起使用 [英] Is there a thing like HTTPContextEnricher thats works with Servicestack and Serilog
问题描述
我正在使用 Servicestack (.Core) 并且它连接到 Serilog.有没有办法用 SessionId、UserId 等内容自动丰富所有日志条目.由于 servicestack 使用它自己的会话和用户处理,serilog-enrichers 将无法工作.
I'm using Servicestack (.Core) and it's connection to Serilog. Is there a way to automatically enrich all Log-Entries with things like SessionId, UserId, etc.. The serilog-enrichers will not work due servicestack uses it's own session and user handling.
亲切的问候
迈克尔
推荐答案
我使用了类似的配置.此代码在 Application_Start
I use a similar configuration.
This code is called on Application_Start
if (Settings.SeqEnabled)
Log.Logger = new LoggerConfiguration()
.Enrich.With<HttpRequestClientHostIPEnricher>()
.Enrich.With<HttpRequestClientHostNameEnricher>()
.Enrich.With<HttpRequestIdEnricher>()
.Enrich.With<HttpRequestNumberEnricher>()
.Enrich.With<HttpRequestRawUrlEnricher>()
.Enrich.With<HttpRequestTraceIdEnricher>()
.Enrich.With<HttpRequestTypeEnricher>()
.Enrich.With<HttpRequestUrlEnricher>()
.Enrich.With<HttpRequestUrlReferrerEnricher>()
.Enrich.With<HttpRequestUserAgentEnricher>()
.Enrich.With<HttpSessionIdEnricher>()
.Enrich.With<ServiceStackUserNameEnricher>()
.WriteTo.Seq(HostContext.AppSettings.GetString("SeqUrl"))
.CreateLogger();
这些扩充器正在使用 SerilogWeb.Classic.Enrichers 命名空间.
These enrichers are using SerilogWeb.Classic.Enrichers namespace.
ServiceStackUserNameEnricher 是我的一个类.
ServiceStackUserNameEnricher is a class of mine.
public class ServiceStackUserNameEnricher : ILogEventEnricher
{
private const string UserNamePropertyName = "UserName";
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if (logEvent == null)
throw new ArgumentNullException(nameof(logEvent));
string str;
try
{
str = HttpContext.Current != null ? HostContext.GetCurrentRequest().GetSession().UserName : null;
}
catch
{
return;
}
if (str == null)
return;
var property = new LogEventProperty(UserNamePropertyName, new ScalarValue(str));
logEvent.AddPropertyIfAbsent(property);
}
}
Serilog 包
<package id="Serilog" version="2.9.0" targetFramework="net46" />
<package id="Serilog.Formatting.Compact" version="1.0.0" targetFramework="net46" />
<package id="Serilog.Sinks.File" version="4.0.0" targetFramework="net46" />
<package id="Serilog.Sinks.PeriodicBatching" version="2.1.1" targetFramework="net46" />
<package id="Serilog.Sinks.Seq" version="4.0.0" targetFramework="net46" />
<package id="SerilogWeb.Classic" version="5.0.52" targetFramework="net46" />
这篇关于有没有像 HTTPContextEnricher 这样的东西可以与 Servicestack 和 Serilog 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!