title: Static class with unique id per request
body: <p>I want to achieve something similar (but much simpler) like Serilog sinks without using DI explicitly.</p>
  <p>It's easy to do with DI you just have to register service as scoped and just create id when object is initialized.</p>
  <p>But how to achieve that with a static class? It's somehow possible because .NET Serilog team did that.</p>
  <p>If you want to use their logger you can simply initialize it:</p>
  <pre><code>Log.Logger = new LoggerConfiguration()
      .Filter.ByExcluding(c =&gt; c.Properties.Any(p =&gt; p.Value.ToString().Contains(&quot;swagger&quot;)))
      .Filter.ByExcluding(c =&gt; c.Properties.Any(p =&gt; p.Value.ToString().Contains(&quot;liveness&quot;)))
      .Enrich.FromLogContext()
      .WriteTo.Console(new ElasticLogFormatter())
      .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(elasticConfiguration.Url))
      {
          AutoRegisterTemplate = true,
          AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6,
          IndexFormat = elasticConfiguration.Index,
          CustomFormatter = new ElasticLogFormatter()
      })
      .CreateLogger();
  </code></pre>
  <p>And whenever you use</p>
  <pre class="lang-cs prettyprint-override"><code>Log.Information(&quot;message&quot;);
  </code></pre>
  <p>it contains a unique request id within a single request despite where you use this (controller, service, db context - they all share the same id).</p>
  <p>I've found <a href="https://github.com/serilog/serilog" rel="nofollow noreferrer">their code</a> on GitHub, but with that, it still remains a struggle to find where and how they achieved that.</p>