Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove properties from log entries in ASP.Net Core

I'm using Serilog with ASP.Net Core 2.0, writing to RollingFile using JsonFormatter.
Followed the instructions here to configure: https://github.com/serilog/serilog-aspnetcore.
Everything works great, but in every log entry I get the following properties that I did not log:

  • SourceContext
  • RequestId
  • RequestPath

I presume they are being added by the ASP.Net Core logging framework. How can I get rid of them?

like image 719
Andrew Avatar asked Nov 08 '17 09:11

Andrew


3 Answers

This can be achieved by plugging an enricher into the logging pipeline:

.Enrich.With(new RemovePropertiesEnricher())

Where:

class RemovePropertiesEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent le, ILogEventPropertyFactory lepf)
    {
        le.RemovePropertyIfPresent("SourceContext");
        le.RemovePropertyIfPresent("RequestId");
        le.RemovePropertyIfPresent("RequestPath");
    }
}
like image 148
Nicholas Blumhardt Avatar answered Nov 15 '22 15:11

Nicholas Blumhardt


Yes, you can get rid of them. Try to use log template:

_loggerConfiguration.WriteTo.Console(LogLevel.Debug, "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level}] {Message}{NewLine}{Exception}");

In this scenario, you won't see mentioned properties in your output.

like image 23
Leonid Avatar answered Nov 15 '22 15:11

Leonid


When you are logging an object, Serilog has the concept of destructuring.

And if you want to remove(ignore) some properties in those objects for logging, there are two options.

  1. You can use attributes. Take a look at this post.
  2. Then there is by-ignoring. You need this Destructurama.ByIgnoring nuget.

Note you should not use both. Using both did not work for me.

like image 1
VivekDev Avatar answered Nov 15 '22 15:11

VivekDev