问题
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.
kind regards
Michael
回答1:
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();
These enrichers are using SerilogWeb.Classic.Enrichers namespace.
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);
}
}
Packages for 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" />
来源:https://stackoverflow.com/questions/60116578/is-there-a-thing-like-httpcontextenricher-thats-works-with-servicestack-and-seri