StuffandBlah
StuffandBlah

Reputation: 1067

PHP logging approach across classes

I've created a simple class LogHelper with a static method that I call within my application. I can call it as follows:

LogHelper::writeToErrorLog($config->getLogPath(), $exception);  or
LogHelper::writeToErrorLog($config->getLogPath(), $exception, $config->getLogFile);

The writeToErroLog method will generate a log filename if one isn't passed into it.

I have another class called Config, which basically takes an XML file and exposes the values via getters & setters. This is initialised at the start of the app & contains the log path where the error logs need to be written to.

My requirements are that I create one log file with the same filename per run of the application. When the app ends the logs, if populated, will be emailed.

My application has numerous other classes for DB, parsing data, formatting data, etc... all requiring logging at some point. The majority of my errors will come from exceptions thrown which will bubble up to the parent class, caught & handled by the LogHelper. There will be several cases where I don't want to throw exceptions and will just want to log information or errors.

My concern is that I feel like I'm constantly passing the config to every class that requires logging, which feels wrong. In addition I only want to be setting the filename for the error log once. Is there any best practice way of approaching this?

TIA

Stuff

Upvotes: 2

Views: 295

Answers (1)

Crashspeeder
Crashspeeder

Reputation: 4311

Have you considered using set_exception_handler()? You wouldn't have to put the logger in every class, it would simply handle all uncaught exceptions. You could call it within your bootstrapping process or some other application initialization spot as such:

set_exception_handler(array("MyClassName", "functionNameHere"));

Inside that function you could call LogHelper::writeToErrorLog().

Upvotes: 1

Related Questions