Is there a thing like HTTPContextEnricher thats works with Servicestack and Serilog

て烟熏妆下的殇ゞ 提交于 2021-01-28 05:40:35

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!