I was having a similar problem where I would need to redact/hide certain fields from an object during logging.
For brevity let's assume object is
public class User
{
public string UserName { get; set; }
public string Password { get; set; }
public override string ToString()
{
return base.ToString();
}
}
Now we log with serilog using the object destructure operator(@)
User user = new User() { UserName = "u", Password = "p" };
_logger.LogWarning("value is {@val}", user);
In order to hide the Password prop we can setup serilog as below
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(new Serilog.Formatting.Json.JsonFormatter())
.Destructure.ByTransforming<User>(_ => new { User = _.UserName })
.CreateLogger();
Now for any logging of object User won't have Password field in it or you can redact Password field by setting Password = "######"
P.S. Ideally we should not log anything sensitive but at times we need to log the whole object where certain props are not desirable to be logged and above is a centralized approach to handle such scenario rather than reviewing every commit in code to verify this potential mistake.