itmannz
itmannz

Reputation: 599

Serilog not surfacing my custom context properties

I am using Serilog with WebApi. I would like to add a Username and class name to every error message.

Here's my code as it stands:

public partial class Repo : BaseRepo<db>
{
    public Repo(ILogger logger) : base(logger)
    {
       /// Not working
       //  Logger.ForContext("UserId", currentuser).ForContext<Repo>();
       logger.ForContext("UserId", currentuser).Information("message")
    }

The message is rendering as:

INF message

How do I get userid: <currentUser> to show?

Upvotes: 2

Views: 1819

Answers (1)

C. Augusto Proiete
C. Augusto Proiete

Reputation: 27868

The message that is displayed for you depends on the output template of the sink you're using (if supported). If you are using the Console Sink, for example, then you need to add {Properties:j} to the outputTemplate parameter when configuring the sink:

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console(LogEventLevel.Debug,
        outputTemplate: "[{Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}")
    .CreateLogger();

Also, if you want to display custom properties that you'll add via LogContext, then you need to Enrich.FromLogContext() too:

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console(LogEventLevel.Debug,
        outputTemplate: "[{Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}")
    .Enrich.FromLogContext()
    .CreateLogger();

Similarly, if you want to display custom properties that you'll add via GlobalLogContext, then you need to Enrich.FromGlobalLogContext() too:

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console(LogEventLevel.Debug,
        outputTemplate: "[{Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}")
    .Enrich.FromGlobalLogContext()
    .CreateLogger();

Upvotes: 6

Related Questions