How to build Exception Logger system in PHP that can have different Logger implementations e.g. File/DB and is testable

StackOverflow https://stackoverflow.com/questions/4031552

Question

I'm building a PHP library that throws various custom Exceptions when it encounters errors. I need to log those exceptions and provide various implementations of the Logger so they could be logged in a file or a database.

The exceptions need to be logged whether they are caught or not, so that excludes implementing any of this in a custom exception handler. Therefore logging needs to be triggered in the constructor of the custom Exception classes themselves.

I also need to unit test, with phpUnit, that the Exception triggers the Logger.

What is the best way of the Exception objects having access to the Logger object?

Ideas/suggestions I've had include:

1) Inject the chosen logger implementation object (or it's Mock object when testing the Exception classes) into the objects that throw the Exceptions, and these objects will then inject the Logger object into the constructor when throwing each new Exception. This could get a bit messy though with the Logger object being passed around all over the place.

2) Use the strategy or a factory pattern (I've read up on the concepts but I'm not sure how to implement these in this case).

Was it helpful?

Solution

That would be

I think the approach of Exceptions having the logger instead of using an Exception Handler is flawed. IMO, it violates the separation of concerns and exceptions should not contain logging logic. However, if you have to have that you could create a custom Exception that has a logger composite as a static member, but that would still leave you with no logging for all Exceptions not subclassed from this Exception. You could change the behavior of PHP's base Exception with runkit but that is dirty black voodoo magic monkeypatching.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top