NLog:将记录器名称限制为Enum或其他结构 [英] NLog: Limit Logger Names to Enum or other structure

查看:70
本文介绍了NLog:将记录器名称限制为Enum或其他结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NLog进行一些日志记录,这要归功于以下答案: 使用NLog将记录器名称导入Excel文件 https://stackoverflow.com/questions/50123661/n-log-in-c-sharp-具有严重性和类别?noredirect = 1#comment87344565_50123661

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");

一切正常,可能就足够了.但是,您会注意到,任何程序员都可以随意在GetLogger中放入他们想要的任何名称,并对其进行拼写错误. "GetLogger("Datobuse").如果程序员不得不从枚举或其他结构中进行选择,那就太好了

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");

这似乎是一个普遍的问题,可能已经有了一个不错的解决方案.我可以想象重写LogManager类,但是不确定具体细节.请注意,LogManager是NLog库中的公共静态类,因此请清除如何隐藏它.另外,还有一个不错的属性,如果您在应用程序项目中一次填写配置文件,只要您将NLog作为参考,该配置文件就可以完美地解决方案中的所有项目.

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.

我将继续创建使用NLog库的库项目,然后将其包含在我的主项目中,除非已经有了一个不错的解决方案.我打赌那里有,但还没见过.

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.

谢谢

戴夫

推荐答案

如果您拥有全局"记录器名称,那么简单的解决方案就是使用全局记录器实例.

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

同一全局NLog Logger实例可以在多个位置使用,而不会出现线程问题.

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

这篇关于NLog:将记录器名称限制为Enum或其他结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆