给定以下类,如何禁止 Serilog 记录 Credentials 属性?
public class SmtpConfigInfo
{
public string SmtpHostName { get; set; }
public int Port { get; set; }
[NotLogged]
public System.Net.ICredentialsByHost Credentials { get; set; }
}
理想情况下,我希望能够仅抑制凭据的“密码”属性。如果没有,我可以接受看到整个凭证暂时被隐藏。但是,当我如下使用 Serilog 登录时,
seriLogger.Error("{@ConfigInfo}", MySmtpConfigInfo)
[NotLogged] 属性被忽略,我可以清楚地看到凭证的所有属性,包括用户名和密码。我看到一个文档似乎表明,如果我的 Credentials 属性被分解为 UserName 和 Password 属性,那么将 [NotLogged] 应用于密码就可以工作。这是我使用“Serilog.Extras.Attributed”的唯一选择吗? 非常感谢!
要启用
NotLogged
属性,您需要添加 .Destructure.UsingAttributes()
- 如果缺少此属性,该属性将被忽略。
示例:
var log = new LoggerConfiguration()
.Destructure.UsingAttributes()
.CreateLogger();
或者,长格式的解决方案类似于:
var log = new LoggerConfiguration()
.Destructure.ByTransforming<SmtpConfigInfo>(info => new {
info.SmtpHostName,
info.SmtpPort,
Credentials = new { UserName = info.Credentials.UserName }
})
.CreateLogger();