PHP.GT

Configuring handlers

LogConfig is the small static registry that controls where log messages go.

The logger itself only decides what level was written. The handlers decide where to write it.

The default handler

If we do nothing else, the first log call creates a default StdOutHandler.

That means this works immediately:

use GT\Logger\Log;

Log::info("Hello from stdout");

If we want to configure the minimum level for that default stdout handler before anything is logged, call:

use GT\Logger\LogConfig;
use GT\Logger\LogLevel;

LogConfig::setDefaultHandlerLevel(LogLevel::NOTICE);

Adding handlers

The main configuration method is LogConfig::addHandler():

LogConfig::addHandler($handler, $minimumLevel, $maximumLevel);
  • The first argument is any LogHandler.
  • The second argument is the minimum level.
  • The third argument is optional and sets the maximum level.

Handlers are appended, not replaced. If two handlers both match the same message, both will receive it.

Writing to a file

use GT\Logger\LogConfig;
use GT\Logger\LogHandler\FileHandler;
use GT\Logger\LogLevel;

LogConfig::addHandler(
	new FileHandler("var/app.log"),
	LogLevel::DEBUG
);

FileHandler opens the file in append mode, so new messages are added to the end.

Writing to stderr

use GT\Logger\LogConfig;
use GT\Logger\LogHandler\StdErrHandler;
use GT\Logger\LogLevel;

LogConfig::addHandler(
	new StdErrHandler(),
	LogLevel::ERROR,
	LogLevel::EMERGENCY
);

This is especially useful for CLI tools, containers, and process supervisors that expect problems on stderr.

Using streams and sockets

StreamHandler currently extends FileHandler without adding extra behaviour. It exists to make stream-based intent clearer in application code.

use GT\Logger\LogConfig;
use GT\Logger\LogHandler\StreamHandler;
use GT\Logger\LogLevel;

LogConfig::addHandler(
	new StreamHandler("php://stdout"),
	LogLevel::DEBUG
);

If PHP can open the path for appending, the handler can write to it.

A common stdout/stderr split

use GT\Logger\LogConfig;
use GT\Logger\LogHandler\StdErrHandler;
use GT\Logger\LogLevel;

LogConfig::setDefaultHandlerLevel(LogLevel::DEBUG);
LogConfig::addHandler(
	LogConfig::getDefaultHandler(),
	LogLevel::DEBUG,
	LogLevel::WARNING
);
LogConfig::addHandler(
	new StdErrHandler(),
	LogLevel::ERROR,
	LogLevel::EMERGENCY
);

Here the default stdout handler is kept only for the lower levels, while the stderr handler receives the more severe range.

Configure once, early

Because the configuration is static, we usually set handlers once near the application’s bootstrap code and then leave them alone.

If we keep calling addHandler() throughout the request, we keep adding more destinations.


Next: Context data