我希望 Serilog 解构任何实现接口(interface)的类(因此我不必手动将它们全部包含在内。)以下似乎不起作用:
public interface ITest { }
public class Test : ITest { }
public class Program
{
public static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.Destructure.ByTransforming<ITest>(i => new { str = "Blah" })
.CreateLogger();
Log.Logger.Debug("We have issues with {@test}", new Test());
}
}
我没有像处理类解构那样获取 {str="Blah"}
,而是获取 {}
是否有技巧可以触发所有实现接口(interface)的解构?
最佳答案
我找到了一种方法。我无法在网上找到任何文档或示例,但我失败了并想出了如何使用解构策略。只需创建一个继承自 IDestructuringPolicy
的类并实现 TryDestructure
方法即可。作为 TryDestructure
的参数,您将获得要解构的值,一个可用于构造结果的工厂对象,最后一个参数是结果的输出参数。如果解构成功,该函数应返回 true
,否则返回 false
。
我创建了一个解构策略来检查传入对象的类型。如果它匹配我想要的接口(interface)类型,我会像正常情况一样解构它并返回 true。
这是我创建的一个示例:
public class ResponseDestructuringPolicy : IDestructuringPolicy
{
public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue result)
{
if (value is IResponse response)
{
result = propertyValueFactory.CreatePropertyValue( new {response.Message} );
return true;
}
result = null;
return false;
}
}
然后在创建它时将其挂接到记录器:
Log.Logger = new LoggerConfiguration()
.Destructure.With(new ResponseDestructuringPolicy())
.CreateLogger();
Destructure.With()
函数可以根据需要采用任意数量的策略。看起来 Serilog 检查已注册的类型解构,然后它将遍历每个策略并在每个策略上运行 TryDestructure
函数,直到它获得 true
。如果没有收到true
,则继续按照默认方式进行解构。
关于c# - Serilog Destructure.ByTransforming<Interface>() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50183335/