c# - 如何将 Serilog.Log.ForContext 与 F# 函数或 C# 方法一起使用
问题描述
使用Serilog和 F# 如何使用.ForContext
with 函数?它似乎只接受类型类:
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
解决方案
方法Type
与它们没有关联,因此您不能使用 theForContext<T>()
或ForContext(Type type)
重载中的任何一个。由于 F# 模块中的函数被编译为静态类(模块)内的静态方法,因此同样适用于它们。作为一个简单的替代方案,您可以SourceContext
自己设置属性:
Log.ForContext("SourceContext", "App.Class.Method")
Log.ForContext("SourceContext", "App.Module.function")
如果您想对重命名操作更加健壮,您可以执行以下操作:
class Class
{
public void Method()
{
var source = $"{typeof(Class).FullName}.{nameof(Method)}";
var logger = Log.ForContext("SourceContext", 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
// 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 source = sprintf "%s.%s" moduleType.FullName (nameof func)
let logger = Log.ForContext("SourceContext", source)
// ...
我要补充一点,通常类/模块名称足以确定消息的来源,因此我建议从源上下文中省略方法/函数名称。这将允许您使用ForContext<T>()
orForContext(Type type)
重载,因此会大大简化事情。
推荐阅读
- hibernate - Kotlin:休眠模型中的属性声明
- xml - 如何将 XmlNodeList 转换为 xml 文件?
- java - 在实体中使用嵌入的 id 类型两次
- python - Tensorflow GPU错误CUDA_ERROR_OUT_OF_MEMORY:内存不足
- picocli - Picocli:类属性填充和应用程序执行的单独职责
- python - Python/Pandas - 替换特定列中值的最有效方法是什么
- mqtt - mqtt 代理桥(在 windows 机器中)
- python - 迭代for循环?
- sql-server - 添加提供程序 MSSQL Linux
- javascript - 在 Javascript 中循环一个模态数组