简体   繁体   中英

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.

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

您需要使用接受Type的重载:

private readonly ILogger _log = Log.ForContext(typeof(DataHelper));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM