Bercovici Adrian
Bercovici Adrian

Reputation: 9360

How to configure Serilog output template for displaying only certain properties

I am trying to configure Serilog to be able to push properties but display only some of them in the log.

Currently my serilog is configured in the following way:

Log.Logger = new LoggerConfiguration().Enrich.FromLogContext()
                .WriteTo.File(logpath)
                .WriteTo
                .Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Properties} {Message}")
                .CreateLogger();

Lets say i have a property called MyProperty and i want only it to be displayed in the log:

string MyProperty="some value";
string MyOtherProperty="some other value";
LogContext.Push("MyProperty",MyProperty);
LogConetext.Push("MyOtherProperty",MyOtherProperty);

When i start logging the Properties section would look like this:

`{SourceContext= "[something]",Myproperty=[...],MyOtherProperty=[...]}`

How can i set the template to show only MyProperty (not even the LogContext)?

I have tried like this to no avail:

outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Properties:MyProperty} {Message}")

Upvotes: 0

Views: 8557

Answers (1)

Xueli Chen
Xueli Chen

Reputation: 12715

It seems that the LogContext is added by default whether you write Enrich.FromLogContext() or not. Here is a wworkaround that you could enrich the logger with the below custom enricher that removes these properties from EventLog.

public class SerilogContextEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        logEvent.RemovePropertyIfPresent("ActionId");
        logEvent.RemovePropertyIfPresent("ActionName");
        logEvent.RemovePropertyIfPresent("RequestId");
        logEvent.RemovePropertyIfPresent("RequestPath");
        logEvent.RemovePropertyIfPresent("CorrelationId");
        logEvent.RemovePropertyIfPresent("MyOtherProperty");
    }
}

Configure it like below:

Log.Logger = new LoggerConfiguration()
            .Enrich.FromLogContext()
            .Enrich.With<SerilogContextEnricher>()
            .WriteTo.File("logs/log.txt")
            .WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Properties} {Message}")
            .CreateLogger();

Upvotes: 1

Related Questions