简体   繁体   English

使用C#类库中的事件实现日志记录功能-好的做法吗?

[英]Implement logging functionality using events in C# class library - is it good practice?

I am facing the challenge of logging implementation in my C# class library, which is a domain model. 我面临着在我的C#类库(一个域模型)中记录实现的挑战。 My main goal is to keep logging functionality as canonical and decoupled as possible. 我的主要目标是保持日志记录功能尽可能规范和分离。 Usually logging messages will be written to files, and perhaps output window while debugging. 通常,日志消息将在调试时写入文件,甚至可能写入输出窗口。

Currently I use log4net, and I have written a static Logger class which implements the logging methods themselves. 当前,我使用log4net,并且编写了一个静态Logger类,该类本身实现了日志记录方法。 So, when methods in the domain objects are executed, they call static Logger.Log() methods. 因此,执行域对象中的方法时,它们将调用静态Logger.Log()方法。

While this wrapping is enough to sooth my purity urges, I wonder if it would be a good idea to implement all this logging calls via events, and remove logging implementation details from the class library altogether. 虽然这种包装足以缓解我的提倡,但我想知道是否可以通过事件实现所有这些日志记录调用,并从类库中完全删除日志记录实现细节,这是否是一个好主意。 Then, client code would optionally listen to them and extract useful information from some LogEventArgs . 然后,客户端代码可以选择侦听它们,并从某些LogEventArgs提取有用的信息。

So the question is: 所以问题是:

Event-based logging in general, and specifically in class libraries, is a good idea or not? 通常,特别是在类库中,基于事件的日志记录是一个好主意吗? And why? 又为什么呢?

Thanks for reading. 谢谢阅读。

Using events for logging also introduces a lot of memory leak possibilities! 使用事件进行日志记录还引入了很多内存泄漏的可能性!

I would use Dependency Injection for cross cutting concerns like logging. 我将使用依赖注入来解决诸如日志记录之类的交叉问题。

With DI you have the possibility to either inject it, or use interception. 使用DI,您可以注入它,也可以使用拦截。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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