PHP Class Registration Approach
I created a simple LogHelper class with a static method that I call in my application. I can call it like this:
LogHelper::writeToErrorLog($config->getLogPath(), $exception); or
LogHelper::writeToErrorLog($config->getLogPath(), $exception, $config->getLogFile);
The writeToErroLog method will generate the name of the log file if not passed to it.
I have another Config class which basically accepts an XML file and provides values ββvia getters and setters. This is initialized at the start of the application and contains the log path to which the error logs should be written.
My requirements are that I create one log file with the same filename per application launch. When the application ends, logs, if full, will be emailed.
My application has many other classes for db, data analysis, data formatting, etc ... all require registration at some point. Most of my errors will come from thrown exceptions that will bubble up to the parent class, caught and handled by the LogHelper. There will be a few cases where I don't want to throw exceptions and just want to log information or errors.
It worries me that I feel like I am constantly passing configuration to every class that requires registration, which seems to be wrong. Also, I only want to specify the filename for the error log once. Is there any better way to approach this?
TIA
Material
source to share
Are you considering using set_exception_handler () ? You wouldn't have to put a logger in every class, it would just handle all uncaught exceptions. You can call it at boot time or elsewhere in the initialization of your application:
set_exception_handler(array("MyClassName", "functionNameHere"));
Within this function, you can call LogHelper::writeToErrorLog()
.
source to share