假设我们正在编写以下结构化日志消息
logger.Info("User's Password is {Password}", "1234567890");我想屏蔽密码属性,因为它是敏感数据。我找到了this issue,但我认为这是一种非常困难的方式。
例如,我发现the extension可以为serilog解决类似的任务。它使用起来非常简单。但是我没有为Nlog找到任何有用的信息。
如何用nlog库实现?如果有任何建议,我将不胜感激。
发布于 2020-04-22 03:26:47
你可以使用RegisterObjectTransformation,introduced in NLog 4.7。
例如:
LogManager.Setup().SetupSerialization(s =>
s.RegisterObjectTransformation<object>(o =>
{
var props = o.GetType().GetProperties();
var propsDict = props.ToDictionary(p => p.Name, p => p.GetValue(o));
propsDict.Remove("password");
return propsDict;
}));请注意,在性能方面,你可能需要像反射缓存和智能优化这样的东西。
发布于 2021-10-07 18:32:35
我建议您将秘密密码封装在一个对象中,如下所示:
public class SecretWrapper : IFormatable
{
private readonly string _secret;
public SecretWrapper(string secret)
{
_secret = secret;
}
public string GetSecret() => _secret; // Not a property to avoid basic reflection
public override string ToString() => "******"
public string ToString (string format, IFormatProvider formatProvider) => ToString();
}NLog永远不会输出secret-value:
logger.Info("User's Password is {Password}", new SecretWrapper("1234567890"));https://stackoverflow.com/questions/61330333
复制相似问题