I'd like to add a Serilog Log
to a static class in my program like this (DataHelper
is the class name):
private readonly ILogger _log = Log.ForContext<DataHelper>();
But this leads to the error message:
static types cannot be used as type arguments
Which makes sense. So how do I inject the logger (which is working fine in non-static classes) to this class?
Update: The answer to you referred question suggests that it is not possible. But according to Serilog's Github, there is a workaround. I just need log to be aware of the class it is logging from. For now, it seems as if it is logging from the main class.
You need to use the overload that accepts a Type
:
private readonly ILogger _log = Log.ForContext(typeof(DataHelper));
The discussion on this issue discusses this limitation and suggests a resolution. Summary: Use the overload ForContext(Type)
, which you can pass the type of the static class using typeof(DataHelper)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With