As you may know I’ve been collaborating with Dapr and I’ve learned that one of the things it enables you to do is to collect traces with the use of the OpenTelemetry Collector and push the events to Azure Application Insights.

After some reading I went and check if I could also write my ASP.NET Core applications to log using the OpenTelemetry Log and Event record definition:

Field NameDescription
TimestampTime when the event occurred.
TraceIdRequest trace id.
SpanIdRequest span id.
TraceFlagsW3C trace flag.
SeverityTextThe severity text (also known as log level).
SeverityNumberNumerical value of the severity.
NameShort event identifier.
BodyThe body of the log record.
ResourceDescribes the source of the log.
AttributesAdditional information about the event.

So here is how you can do it:

Create an ASP.NET Core application

1dotnet new webapi -n aspnet.opentelemetry
2cd aspnet.opentelemetry

Add a reference to the OpenTelemetry libraries

1dotnet add package OpenTelemetry.Extensions.Hosting --prerelease 
2dotnet add package OpenTelemetry.Exporter.Console --prerelease   

Modify the CreateHostBuilder method in Program.cs

 1public static IHostBuilder CreateHostBuilder(string[] args) =>
 2  Host.CreateDefaultBuilder(args)
 3      .ConfigureLogging(logging =>
 4      {
 5          logging.ClearProviders();
 6          logging.AddOpenTelemetry(options =>
 7          {
 8              options.AddProcessor(new SimpleExportProcessor<LogRecord>(new ConsoleExporter<LogRecord>(new ConsoleExporterOptions())));
 9          });
10      })
11      .ConfigureWebHostDefaults(webBuilder =>
12      {
13          webBuilder.UseStartup<Startup>();
14      });

The code first clears all logging providers and then adds OpenTelemetry using the SimpleExportProcessor and ConsoleExporter.

Please check the OpenTelemetry .NET API repo to learn more.

Modify the log settings

Edit the appsettings.Development.json in order to configure the default log settings using the OpenTelemetry provider:

 2  "Logging": {
 3    "LogLevel": {
 4      "Default": "Information",
 5      "Microsoft": "Warning",
 6      "Microsoft.Hosting.Lifetime": "Information"
 7    }
 8  },
 9  "AllowedHosts": "*"

Test the program

Run the following command to test the application.

1dotnet run

You should see the logs, formatted as OpenTelemetry log records, written in the console:

LogRecord.State:Application is shutting down…

Both TraceId and SpanId will get filled when a request is handled by your application and if the call is made by Dapr it will respect the values sent by it so you can correlate traces and logs improving the observability of your solution.

Hope it helps! and please find the complete code here