serilog / serilog-extensions-logging

Serilog provider for Microsoft.Extensions.Logging
Apache License 2.0
307 stars 97 forks source link

System.Diagnostics.Activity.Current is Null when UseSeriLog() #174

Closed avireddy02 closed 4 years ago

avireddy02 commented 4 years ago

In the middleware, i'm using System.Diagnostics.Activity.Current to get hold of TraceId which is null when I add .UseSerilog() to IHostBuilder. Also i'm using AspNetCore implementation of Trace Context "System.Diagnostics.Activity.DefaultIdFormat = ActivityIdFormat.W3C;" which is new standard to log Correlation Id in Aspnetcore 3.*

Framework: AspNetCore 3.1 Program.cs

       public static void Main(string[] args)
        {
            System.Diagnostics.Activity.DefaultIdFormat = ActivityIdFormat.W3C;
            CreateHostBuilder(args).Build().Run();
        }
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            }).UseSerilog();

In middleware: System.Diagnostics.Activity.Current.TraceId.ToString()

Exception: Object reference not set to an instance. because System.Diagnostics.Activity.Current is null

nblumhardt commented 4 years ago

Hi! To help, we'll need some idea of what the middleware looks like, where it sits in the pipeline, and what the stack trace of the exception is - thanks!

avireddy02 commented 4 years ago

@nblumhardt I have uploaded a sample repo with middleware and serilog config Sample Code in GitHub

skomis-mm commented 4 years ago

Hi @avireddy02 ,

According to the source, Activity starts if logging is enabled.

So in your sample you need to preconfigure Serilog logger first . It works by default because of standard MEL logging enabled (Console, Debug)

avireddy02 commented 4 years ago

@skomis-mm Will you able to point me to an example on how to preconfigure?

skomis-mm commented 4 years ago

@avireddy02 look here for an example

Log.Logger = new LoggerConfiguration()
   // ...
   .CreateLogger();
avireddy02 commented 4 years ago

@nblumhardt & @skomis-mm Above suggestion worked. Thank you!!! 🙏