Using Serilog and F# how to use .ForContext
with functions? it appears it only accepts type classes:
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
What would be the right way to add the context of a F# function or a C# method (which I presume should be the same problem)?
So far my solution has been using this function which return SourceContext exactly as using a class (moduleFullName+className
):
let logFromFn _ =
Serilog.Log.ForContext
("SourceContext",
StackTrace().GetFrame(1).GetMethod().DeclaringType
|> fun dt -> dt.FullName + "+" + dt.Name)
- As stated in this answer, it might be expensive, I use it in places where it would be called once in the whole program.
- It works well in F# functions inside modules, not so good in for example, the entry point file, where it returns
program+program