Search code examples
loggingserilog

Add type name of ForContext<T> to the message template


I want to always prefix log messages with what class they have been emitted from. It can be done manually, but it would be nice if it was possible to do it automatically, so not every log call needs to explicitly include the ambient context.

Is it possible to use e.g. ForContext and then have the instance type name of T logged, by including it in the message template of the logging configuration?

public class Foo
{
    public Foo(ILogger logger)
    {
        var logger = logger.ForContext<Foo>();
        logger.Information("Bar"); // written log message should include both "Foo" and "Bar"
    }
}

Solution

  • Yes, that's the idea of the Source Context; ForContext adds a tag into the LogEvent that's captured, which has key: SourceContext and value Namespace.Foo. You'll need to include {SourceContext} or {Properties} in the message template for it to be emitted though.

    I doubt this isn't a duplicate, I hope someone takes the time to find a more complete answer and close this one ;)


    The other thing I'd suggest is to read https://serilog.net - IME in general the more you follow the spirit of structured logging, the less you'll rely on the Source Context in your log messages.