NLog 结构化日志屏蔽
NLog structuring logging masking
假设我们正在编写以下结构化日志消息
logger.Info("User's Password is {Password}", "1234567890");
我想屏蔽密码 属性 因为它是敏感数据。我找到了 this issue 但我认为这是一个非常困难的方法。
例如,我发现 the extension 解决了 serilog 的类似任务。使用起来非常简单。但是我没有找到任何对Nlog有用的信息。
如何用nlog库实现?
我将不胜感激任何建议。
您可以使用 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;
}));
请注意,就性能而言,您可能需要反射缓存和智能优化之类的东西。
我建议您将秘密密码包装在这样的对象中:
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 永远不会输出秘密值:
logger.Info("User's Password is {Password}", new SecretWrapper("1234567890"));
假设我们正在编写以下结构化日志消息
logger.Info("User's Password is {Password}", "1234567890");
我想屏蔽密码 属性 因为它是敏感数据。我找到了 this issue 但我认为这是一个非常困难的方法。
例如,我发现 the extension 解决了 serilog 的类似任务。使用起来非常简单。但是我没有找到任何对Nlog有用的信息。
如何用nlog库实现? 我将不胜感激任何建议。
您可以使用 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;
}));
请注意,就性能而言,您可能需要反射缓存和智能优化之类的东西。
我建议您将秘密密码包装在这样的对象中:
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 永远不会输出秘密值:
logger.Info("User's Password is {Password}", new SecretWrapper("1234567890"));