使用Serilog和 F# 如何使用.ForContextwith 函数?它似乎只接受类型类:
type A()=
log = Serilog.Log.ForContext<A>() // ✅
let f _ =
log = Serilog.Log.ForContext<f>() // compile error
log = Serilog.Log.ForContext(f.GetType()) // the information is not the same as A where it gives module + type path
添加 F# 函数或 C# 方法的上下文的正确方法是什么(我认为应该是同一个问题)?
到目前为止,我的解决方案一直在使用这个函数,它返回 SourceContext 与使用类 ( moduleFullName+className) 完全相同:
let logFromFn _ =
Serilog.Log.ForContext
("SourceContext",
StackTrace().GetFrame(1).GetMethod().DeclaringType
|> fun dt -> dt.FullName + "+" + dt.Name)
- 如this answer中所述,它可能很昂贵,我在整个程序中会调用一次的地方使用它。
- 它在模块内的 F# 函数中运行良好,例如在它返回的入口点文件中不太好
program+program