Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Serilog ILogger to a static class

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.

like image 619
disasterkid Avatar asked Nov 07 '18 14:11

disasterkid


2 Answers

You need to use the overload that accepts a Type:

private readonly ILogger _log = Log.ForContext(typeof(DataHelper));
like image 152
Nicholas Blumhardt Avatar answered Nov 07 '22 03:11

Nicholas Blumhardt


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).

like image 2
Tom W Avatar answered Nov 07 '22 04:11

Tom W