简体   繁体   中英

Log the type used with the generic ILogger<T> via Serilog

I am currently using this output template with Serilog:

"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] [{MachineName}] {Message:lj}{NewLine}{Exception}"

I would like to add the class that I specify when declaring the Microsoft.Extensions.Logging.ILogger logger that I inject, ie if I declare ILogger<MyType> then I would like to output MyType via the template.

I know I can add the whole context but I read that this comes with a performance penalty, so currently I add the class by adding nameof(MyType) to each message - which is a mess.

Is there an enricher or something similar that will make the type available in the template (or just prefix each log message with the type)?

Edit:

There isn't much code really, this is how I configure Serilog with the dotnet-core WebApi:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseStartup<Startup>();
    })
    .UseWindowsService()
    .UseSerilog();

And this is an example of how I use the logger via IOC:

private readonly ILogger<MyType> _logger;

public MyType(ILogger<MyType> logger)
{
    _logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

public void HelloLog()
{
   _logger.LogInformation("hello");
}

// expected log output: "[MyType] hello"

I understand from Andy's comment that I could write a LoggingProvider and pass it in the UseSerilog overload that takes a collection of providers. That is something I will look into if nothing easier turns up.

The type name should be added into the SourceContext property of any log events emitted by the ILogger<T> , exactly as if you'd used the ForContext<T>() or ForContext(type) methods on a Serilog.ILogger . Using {SourceContext} somewhere in your message template should allow you to add just the source name, eg

"[{Timestamp:HH:mm:ss} {Level:u3}] [{MachineName}] [{SourceContext}] {Message:lj}{NewLine}{Exception}"

Note that this will output the full name of the type, so will include the namespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM