11

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.

disasterkid
  • 6,948
  • 25
  • 94
  • 179
  • Possible duplicate of [Dependency injection with a static logger, static helper class](https://stackoverflow.com/questions/1293489/dependency-injection-with-a-static-logger-static-helper-class) – nilsK Nov 07 '18 at 14:27
  • @nilsK the answer to you referred question suggests that it is not possible. But according to Serilog's Github, there is a way: https://github.com/serilog/serilog/issues/886 – disasterkid Nov 07 '18 at 14:39
  • what I would do, if you have a possibility, refactor DataHelper class and make in regular object registered as a singleton. It will simplify usage and testability – OlegI Nov 07 '18 at 14:48
  • @OlegI Does that mean that every static class I have made, in order to write to log, needs to turn into Singleton? – disasterkid Nov 07 '18 at 14:54
  • @Disasterkid well, it's up for you to make such decisions if there is no easy workaround to fix your problem and writing logs are crucial for you – OlegI Nov 07 '18 at 14:59

2 Answers2

21

You need to use the overload that accepts a Type:

private readonly ILogger _log = Log.ForContext(typeof(DataHelper));
Nicholas Blumhardt
  • 30,271
  • 4
  • 90
  • 101
  • 1
    Do we not need `static` after `private`? – disasterkid Nov 08 '18 at 08:32
  • 1
    Depends on usage; I only made the minimal changes here to show the `ForContext()` overload in the setting of your code sample above. If the `_log` field is in a static class, you'll definitely need to add `static`; otherwise, it's probably a matter of taste in this situation. HTH! – Nicholas Blumhardt Nov 09 '18 at 00:55
2

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

Tom W
  • 5,108
  • 4
  • 30
  • 52