首页 > 解决方案 > 如何将 Serilog.Log.ForContext 与 F# 函数或 C# 方法一起使用

问题描述

使用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)
  1. this answer中所述,它可能很昂贵,我在整个程序中会调用一次的地方使用它。
  2. 它在模块内的 F# 函数中运行良好,例如在它返回的入口点文件中不太好program+program

标签: c#f#serilog

解决方案


方法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)重载,因此会大大简化事情。


推荐阅读