Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When Serilog [NotLogged] attribute is applied to NetworkCredential object

Tags:

serilog

Given the following class, how do I suppress the Credentials property from being logged by Serilog?

public class SmtpConfigInfo
{
    public string SmtpHostName { get; set; }

    public int Port { get; set; }

    [NotLogged]
    public System.Net.ICredentialsByHost Credentials { get; set; }
}

Ideally, I would like to be able to suppress only the "Password" property of Credentials. If not, it's acceptable for me to see the whole Credentials being suppressed for now. However, when I log with Serilog as follows,

seriLogger.Error("{@ConfigInfo}", MySmtpConfigInfo)

the [NotLogged] attribute is ignored and I see all properties of Credentials including UserName and Password in the clear. I saw a documentation that seems to indicate that if my Credentials property were broken down to UserName and Password properties, then applying [NotLogged] to Password could work. Is that the only option I have using "Serilog.Extras.Attributed"? Thanks much!

like image 899
SamDevx Avatar asked Dec 05 '25 14:12

SamDevx


1 Answers

To enable the NotLogged attribute you need to add .Destructure.UsingAttributes() - if this is missing the attribute will be ignored.

Edit: as @seangwright pointed out, Destructure.UsingAttributes is available in the Destructurama.Attributed nuget package, so make sure you add a reference to that library in your project before you continue.

Example:

var log = new LoggerConfiguration()
    .Destructure.UsingAttributes()
    .CreateLogger();

Alternatively, the long-form solution is something like:

var log = new LoggerConfiguration()
    .Destructure.ByTransforming<SmtpConfigInfo>(info => new {
        info.SmtpHostName,
        info.SmtpPort,
        Credentials = new { UserName = info.Credentials.UserName }
    })
    .CreateLogger();
like image 124
Nicholas Blumhardt Avatar answered Dec 08 '25 22:12

Nicholas Blumhardt