使用 Serilog和F#如何使用.ForContext
有功能吗?它似乎只接受类型类:
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)
program+program
最佳答案
方法没有 Type
与它们相关联,因此您不能使用 ForContext<T>()
中的任何一个或 ForContext(Type type)
过载。由于 F# 模块中的函数被编译为静态类(模块)内的静态方法,因此同样适用于它们。作为一个简单的替代方法,您可以设置 SourceContext
自己的属性(property):
let propName = Serilog.Core.Constants.SourceContextPropertyName
Log.ForContext(propName, "App.Class.Method")
Log.ForContext(propName, "App.Module.function")
如果您想对重命名操作更加健壮,您可以执行以下操作:class Class
{
public void Method()
{
var source = $"{typeof(Class).FullName}.{nameof(Method)}";
var logger = Log.ForContext(Core.Constants.SourceContextPropertyName, source);
// ...
}
}
module Module =
// It's a bit fiddly to get the module type in F#, but here's one
// approach (credit https://stackoverflow.com/a/14706890/7694577).
type private Marker = interface end
let private moduleType = typeof<Marker>.DeclaringType
let loggerFor name =
let source = sprintf "%s.%s" moduleType.FullName name
let propName = Serilog.Core.Constants.SourceContextPropertyName
Log.ForContext(propName, source)
// Requires the `nameof` operator from F# 4.7 preview.
// The function needs to be recursive since it is referenced when calling `nameof`.
let rec func () =
let logger = loggerFor (nameof func)
// ...
我要补充一点,通常类/模块名称足以确定消息的来源,因此我建议从源上下文中省略方法/函数名称。这将允许您使用 ForContext<T>()
或 ForContext(Type type)
重载,因此会大大简化事情。
关于c# - 如何将 Serilog.Log.ForContext 与 F# 函数或 C# 方法一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63746000/