4 ms·
Still it doesn't necessarily do much more than the hard-coded "fprintf($f, '%s [%s] %s - %s', $this->machineName, date('Y-m-d H:i:s'), $level, $message);" alrea
by lux 15y ago
Still it doesn't necessarily do much more than the hard-coded "fprintf($f, '%s [%s] %s - %s', $this->machineName, date('Y-m-d H:i:s'), $level, $message);" already does in the original, unless you want to override it separately.
I'd probably do something more like this:
public $format = '%s [%s] %s - %s'; // machine, date, level, message
public function formatMessage ($level, $message) {
return sprintf ($this->format, $this->machine, date('Y-m-d H:i:s'), $level, $message);
}
public function log ($level, $message) {
return $this->write ($this->formatMessage ($level, $message));
}
That way you could change the format with no subclassing needed:
$logger->format = '%s, %s, %s, %s';
I also like the idea of using a stream wrapper to override the logFile property:
$logger->logFile = 'db://user:pass@localhost';
So again instead of subclassing, you just implement a stream wrapper as shown here:
http://www.php.net/manual/en/stream.streamwrapper.example-1.php http://www.php.net/manual/en/stream.streamwrapper.example-1....
Perhaps that's just my personal aversion to needless depth in class hierarchy talking though... :)
Edit: Wow does this thread have me geeking out! Haha, cheers :)
- randallsquared 15y agoI'm intrigued by the stream wrapper idea, but I don't think your "change the format" is general enough... sure, you can change the format, as long as you change it to something that uses the other arguments sprintf is being passed, but that's a pretty strong restriction. Maybe it would be workable if you had log() take optional argument(s) that represent the args to sprintf, too, but I'm not sure that it's worth it.
- lux 15y agoTrue, and using %1$s style references in the format in order to change their ordering is a lot uglier than overriding a method. In my last example, I did provide a formatMessage() which was the equivalent of the createLogMessage() for purposes of overriding. Best of both worlds :)