Let’s consider i have a model.
public record UserRegisterModel(string Email, string Password);
When log this object i want to ignore Email
and mask Password
property for example.
logger.LogInformation("User register request - {@obj}", obj);
Expected output:
"User register request - { "$type" : "UserRegisterModel", "Password" : "**********" }"
The Destructurama.Attributed package provides convenient ways to configure Serilog complex object logging by using attributes.
With these, you can easily ignore some properties, apply masking and so on. But this attribute-based approach does introduce a dependency on Serilog in projects where such a dependency may be undesirable (a similar issue exists with Entity Framework Core and its attribute-based model configuring approach).
UserRegisterModel([property: NotLogged] string Email, [property: LogMasked] string Password);
MY SOLUTION:
I’ve developed a library, Serilog.FluentDestructuring, which simplifies the destructuring process by introducing a Fluent API. This allows developers to define object destructuring behavior in a clean, readable, and concise manner, reducing the verbosity of the configuration.
CODE EXAMPLE:
public class ApplicationFluentDestructuringPolicy : FluentDestructuringPolicy
{
protected override void Configure(FluentDestructuringBuilder builder)
{
builder.Entity<UserRegisterRequest>(e =>
{
e.Property(p => p.Email)
.Mask();
e.Property(p => p.Password)
.Ignore();
});
}
}
var cfg = new LoggerConfiguration()
.Destructure.WithFluentDestructuringPolicy<ApplicationFluentDestructuringPolicy>()
...
Please leave any feedback you want.
I tried to find an implementation of my idea but found nothing similar, so I wrote it myself.
Andrey Bespalov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.