3

I am facing the challenge of logging implementation in my C# class library, which is a domain model. 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. So, when methods in the domain objects are executed, they call static Logger.Log() methods.

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.

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.

heltonbiker
  • 26,657
  • 28
  • 137
  • 252
  • 4
    This is my opinion, but I think that would leave you creating a bunch of unecessary events in your code where the only listener would be a logging handler. That seems particularly difficult to justify in my mind. If you really want to DRY up your code, you might look into an AOP framework like [PostSharp](http://www.postsharp.net/) that can add logging to your code without making your eyes bleed. – Josh Nov 19 '13 at 13:20
  • @Josh well, I partially agree, although I would try to invest in a "rich LogEventArgs", so that I would have very few, or even just one "Logger.Log()" one-liner per log event. (well, perhaps this is easier to say than to make...) – heltonbiker Nov 19 '13 at 13:28
  • As a side note: the logger as a static class makes your code harder to test. – BartoszKP Nov 19 '13 at 13:29
  • @BartoszKP - Not necessarily. You can still provide dependency injection for the real logger on a static class, and it saves you from having to make **every** class in your application dependent on the logger. A static class with a `SetLogger(Ilogger logger)` method on it is just as testable, but makes it more accessible in your code. – Josh Nov 19 '13 at 13:45
  • @Josh Not every, only the "service" classes. Fair point though, I agree :) – BartoszKP Nov 19 '13 at 13:47

1 Answers1

3

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.

Nickolai Nielsen
  • 932
  • 6
  • 19