【问题标题】:When Serilog [NotLogged] attribute is applied to NetworkCredential object当 Serilog [NotLogged] 属性应用于 NetworkCredential 对象时
【发布时间】:2015-02-21 21:48:13
【问题描述】:

鉴于以下类,我如何禁止 Serilog 记录 Credentials 属性?

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

    public int Port { get; set; }

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

理想情况下,我希望能够仅取消凭据的“密码”属性。如果没有,我现在可以看到整个 Credentials 被压制。但是,当我按如下方式使用 Serilog 登录时,

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

[NotLogged] 属性被忽略,我清楚地看到凭据的所有属性,包括用户名和密码。我看到一个文档似乎表明如果我的 Credentials 属性被分解为 UserName 和 Password 属性,那么将 [NotLogged] 应用于 Password 可以工作。这是我使用“Serilog.Extras.Attributed”的唯一选择吗? 非常感谢!

【问题讨论】:

    标签: serilog


    【解决方案1】:

    要启用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();
    

    【讨论】:

    • 我对这个答案有点困惑。你说你需要.Destructure.UsingAttributes(),但那并没有出现在代码中。
    • 道歉-它们是两种不同的解决方案;您可以应用.Destructure.UsingAttributes() 配置和[NotLogged],您可以使用上面的“长格式”.Destructure.ByTransforming() 代码。干杯!
    • 我正在使用 Serilog v2.5.0 并且还引用了 Destructurama.Attributed。但是“new LoggerConfiguration().Destructure.UsingAttributes()”会引发编译时错误。像“LoggerDestructuringConfiguration”不包含“UsingAttributes”的定义,并且找不到接受“LoggerDestructuringConfiguration”类型的第一个参数的扩展方法“UsingAttributes”(您是否缺少 using 指令或程序集引用?)。请帮忙
    • @Raghu Serilog 中的属性解构支持已移至 Destructurama.Attributed 项目 (github.com/destructurama/attributed)。除此之外,很多新功能还没有作为当前 nuget 包的正式版本发布,这意味着你需要在 VS 的 nuget UI 中检查“include prerelease”。
    猜你喜欢
    • 1970-01-01
    • 2014-11-02
    • 2021-09-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多