Serilog:是否有通过属性名忽略解构属性的工具包?
在Serilog中通过属性名忽略解构属性的方案
是的,你可以通过以下两种方式实现直接按属性名忽略解构属性:
1. 自定义解构策略实现
你可以自行实现Serilog的IDestructuringPolicy接口,编写逻辑来忽略指定属性名的字段。示例代码如下:
using Serilog.Core; using Serilog.Events; using System.Reflection; public class IgnorePropertiesByNamePolicy : IDestructuringPolicy { private readonly HashSet<string> _propertyNamesToIgnore; public IgnorePropertiesByNamePolicy(params string[] propertyNames) { _propertyNamesToIgnore = new HashSet<string>(propertyNames, StringComparer.OrdinalIgnoreCase); } public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue result) { if (value == null || value.GetType().IsPrimitive || value is string) { result = null; return false; } var properties = value.GetType() .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => !_propertyNamesToIgnore.Contains(p.Name)) .Select(p => new LogEventProperty(p.Name, propertyValueFactory.CreatePropertyValue(p.GetValue(value)))); result = new StructureValue(properties); return true; } }
然后在Logger配置中添加这个策略:
Log.Logger = new LoggerConfiguration() .Destructure.With(new IgnorePropertiesByNamePolicy("Password", "Token")) // 其他日志配置 .CreateLogger();
2. 第三方工具包扩展
Destructurama.ByIgnoring虽以Lambda表达式为主要指定方式,但你可以基于它封装一个接受属性名的扩展方法;部分社区衍生的Serilog扩展包也支持直接传入属性名忽略字段。不过自定义解构策略的方式灵活度更高,无需依赖额外包即可满足需求。
内容的提问来源于stack exchange,提问作者ertucode
相关产品推荐
相关产品推荐

