2

I am aware that logging is a cross cutting concern and I normally use AOP for logging any errors or exceptions in general. However I am facing a scenario where we also have to log specific information about various operations performed, like for example when an operation was successful we have to log that also, we also have to log something if the response from a web service is invalid according to our business rules etc etc. This means that in some scenarios, logging an event becomes specifically part of the business flow and in these specific cases it is not a cross cutting concern.

To handle such scenarios I have made a DBLogger class that simply writes some dynamic messages and error codes to the DB.

Currently I am using the DBLogger class via dependency injection from ILogger interface. When I look at my code it seems like a code smell to me to see that I am injecting this class in every class where I need to log business rules violation. I am considering making the DBLogger class static and using it directly instead of injecting it. This will remove the code clutter a little bit and my constructor will be clean but the dependency will be still there.

My question is what is the recommended way and best practice to handle such scenarios, and how can OOP and design patterns come to rescue in this case to stop me from violating the Open Closed Principal?

4

2 回答 2

3

为了单元测试,我喜欢注入记录器。它可以更轻松地模拟记录器并避免在单元测试中定义真实记录器的依赖关系。

此外,如果您的 IOC 容器已经为您定义了它,那么注入它是透明且省力的。

于 2013-11-13T06:05:06.013 回答
0

“......在某些情况下,记录事件成为业务流程的特定部分,在这些特定情况下,它不是一个横切关注点。”

听起来它应该进行单元测试。因此应该注入。

考虑装饰,或者像 TGH 强调的那样,使用基类来减少噪音。

于 2013-11-13T08:51:37.603 回答