NLog: Limit Logger Names to Enum or other structure

蹲街弑〆低调 提交于 2019-12-11 14:53:41

问题


I am using NLog for some logging and thanks to these answers: Getting Logger Name into Excel file with NLog https://stackoverflow.com/questions/50123661/nlog-in-c-sharp-with-severity-and-categories?noredirect=1#comment87344565_50123661

I am able to log different types of events (ex: "Thermal", "Database",etc.) to a single file with the logger field showing the type of event. One simply calls for example:

NLog.LogManager.GetLogger("Database").Debug("Error writing to DB");

This all works fine and might be enough. However, you'll notice that any programmer is free to put any name they want in GetLogger AND misspell it. "GetLogger("Datobuse"). It would be nice if the programmer had to choose from an enum or other structure:

NLog.LogManager.GetLogger(LoggerNames.Database).Debug("Error writing to DB");

This seems like it might be a common problem and might already have an elegant solution. I can imagine overriding the LogManager class but am not sure of the specifics. Note that LogManager is a public static class in the NLog library so not clear how to hide it. Also, there is the nice property that if you fill in the config file once in your app project, the config file works perfectly for all the projects in the solution as long as you include NLog as a reference.

I'll go down the path of creating a library project that makes use of NLog library and then include that it my main project UNLESS there is already a great solution. I'm betting there is, but haven't seen one.

Thanks,

Dave


回答1:


If you have "global" logger names, then the easy solution is just to use global logger instances.

The same global NLog Logger instance can be used by multiple locations without getting into threading issues.



来源:https://stackoverflow.com/questions/50373756/nlog-limit-logger-names-to-enum-or-other-structure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!