Log4net - 使用继承时的最佳策略
我已将 log4net 集成到我的应用程序中。我有一些辅助方法来帮助记录调用 log4net 的日志。重构时,我计划将这些方法移至基类,以便代码不会在其他派生类中重复。
如果没有继承模型,则以下内容在每个类中都可以正常工作
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
将上述内容放入基类中将返回声明类型作为基类而不是派生类。
将此声明移动到基类的最佳方法是什么?
目前,我可以想到一些方法来实现这一目标,但发现它们不是最佳的。
I have integrated log4net in my app. I have a few helper methods to assist in logging which call log4net. When refactoring, I plan to move these methods to base class so that the code is not repeated in other derived classes.
Without the inheritance model, following worked correctly in each class
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Placing the above in the base class will return the declaring type as base class and not derived class.
What is an optimal way to move this declaration to the base class?
At present, I can think of a few ways to achieve this but don't find them optimal.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想我会这样做:
I think I would do this:
根据 Sefan 的回答,这是我在基类中声明它的方式
Based on Sefan's answer here's how I declared it in the base class
我们只需在需要记录器的每个类中重新声明它(其要点是私有静态),并使用代码片段使其变得像键入
log一样简单;
如果你想要额外的花哨,你可以这样做:并通过你的继承层次结构打孔 T,使其成为最派生的类。
这里所有答案的问题是您丢失了有关日志消息来自何处的信息,因此尽管添加了样板,我个人仍会坚持使用原始代码。
We just redeclare it in each class that needs a logger (the point of it being a private static) and use a code snippet to make that as simple as typing
log<tab><tab>
if you wanted to get extra fancy though you could do something like:And punch T through your inheritance hierarchy so that it is the most derived class.
The problem with all of the answers here is that you lose information about where log messages are coming from, so I would personally stick to your original code despite the added boilerplate.