Paul Turner
Paul Turner

Reputation: 39625

How do I add cross-cutting information to Microsoft.Extensions.Logging events?

I'm trying to set up a basic prototype of client-server applications, both using ASP.NET Core 2.0. As part of this, I'm sending diagnostic information to Seq. In the Startup class for each application, I'm using Seq.Extensions.Logging and configuring the Seq sinks as follows:

public void ConfigureServices(IServiceCollection services)
{
    services.AddLogging(builder =>
    {
        builder
            .SetMinimumLevel(LogLevel.Debug)
            .AddSeq();
    });

This works; all the events appear in Seq. However, it's not possible to easily distinguish which application any specific event is from.

In the past, using Serilog, I have been able to add propertes to the logger which are included in every event. Typically I would add the name of the application and the host it is running on as a pair of additional properties:

Log.Logger = new LoggerConfiguration()
    .Enrich.WithMachineName()
    // ...other configuration...
    .CreateLogger();

Is there a way to configure the Microsoft logging extensions to do the same thing?

Upvotes: 2

Views: 647

Answers (1)

Edward
Edward

Reputation: 29996

There are two options for you.

  1. Use built-in Seq feature.

For Seq, it provides API Keys which is used to identity the client application. You could add the Applied properties with the specific name like your project name, and configure the api key by

            services.AddLogging(loggingBuilder =>
        {
            loggingBuilder.AddSeq(Configuration.GetSection("Seq"));
        });

Or

            services.AddLogging(loggingBuilder =>
        {                
            loggingBuilder.AddSeq("http://xxx:5341", apiKey: "K5HzACIfiQxr67CKlvUj");
        });
  1. Use Serilog to configure the output template like

            var output = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message} {ActionName} {UserName} {NewLine}{Exception} {MachineName}";
    
        Log.Logger = new LoggerConfiguration()
               .Enrich.FromLogContext() // Populates a 'User' property on every log entry
               .Enrich.WithProperty("MachineName", Environment.MachineName) //new field
               .WriteTo.RollingFile("Logs/app-{Date}.txt", outputTemplate: output)
               .WriteTo.Seq("http://xxx:5341",apiKey: "K5HzACIfiQxr67CKlvUj")
               .CreateLogger();
        loggerFactory
            //.AddFile("Logs/app-{Date}.txt")
            .AddSerilog();
    

Upvotes: 0

Related Questions