简体   繁体   中英

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?

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();

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