Pankaj
Pankaj

Reputation: 1524

serilog intercept logs and modify log

I want to intercept the logs which are about to be written by serilog and modify it based upon some logic, i.e, look for some sensitive information in the logs and mask it.

The closest I have reached till the point is to find ILogEventEnricher

public class LogEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
       //do something here, but what?
    }
}

but the property MessagTemplate of LogEvent is readonly. Any Idea how can I intercept the logs and modify them before logging.

Upvotes: 3

Views: 3404

Answers (1)

C. Augusto Proiete
C. Augusto Proiete

Reputation: 27868

A common way to deal with that with Serilog, is to tell Serilog not to log certain properties when destructuring objects.

For example, via Destructurama.Attributed:

public class LoginCommand
{
    public string Username { get; set; }

    [NotLogged]
    public string Password { get; set; }
}

You can read more in this blogpost: Using attributes to control destructuring in Serilog.


You can also do something similar via Destructurama.ByIgnoring

Log.Logger = new LoggerConfiguration()
    .Destructure.ByIgnoringProperties<User>(u => u.Password)
    // Other logger configuration
    .CreateLogger()

Upvotes: 2

Related Questions