PHP.GT

Custom log handlers

The built-in handlers cover the common destinations:

  • stdout
  • stderr
  • files
  • generic stream paths

When that is not enough, we can create a custom handler by extending GT\Logger\LogHandler\LogHandler or one of its subclasses.

The smallest useful customisation

Quite often we do not need a completely new destination. We just want a different way of formatting context.

In that case, extending FileHandler is usually the simplest path:

use GT\Logger\LogHandler\FileHandler;

class JsonContextFileHandler extends FileHandler {
	protected function unwrapContext(array $context):string {
		return json_encode($context, JSON_UNESCAPED_SLASHES) ?: "";
	}
}
use GT\Logger\LogConfig;
use GT\Logger\LogLevel;

LogConfig::addHandler(
	new JsonContextFileHandler("var/json.log"),
	LogLevel::INFO
);

This keeps all of FileHandler’s file-opening and line-writing behaviour, while changing how the context part is rendered.

Writing a handler from scratch

When the destination itself is different, extend the abstract base class:

use GT\Logger\LogHandler\LogHandler;

class PhpErrorLogHandler extends LogHandler {
	public function handle(
		string $level,
		string $message,
		array $context = []
	):void {
		error_log($this->getLogLine($level, $message, $context));
	}

	protected function unwrapContext(array $context):string {
		$parts = [];

		foreach($context as $key => $value) {
			$parts[] = "$key=" . (is_scalar($value) || $value === null
				? (string)$value
				: get_debug_type($value));
		}

		return implode(" ", $parts);
	}
}

LogHandler gives us:

  • the log line token constants
  • the default format parts
  • the getLogLine() helper that assembles the final string

We only need to decide how to write the line and how to render the context.

When to extend StreamHandler

At the moment, StreamHandler does not add behaviour on top of FileHandler.

It is still a reasonable class to extend if the destination is stream-like and we want the name to reflect that intention in our codebase.


Next: WebEngine integration