Quick start guide
In this guide we will install the package, write the first log line, and then add one or two handlers so the output goes where we expect.
1. Install the package
composer require phpgt/logger
2. Write the first log line
use GT\Logger\Log;
Log::info("Application started");
With no other setup, the library creates a default stdout handler the first time a log message is written.
That makes it very easy to start, especially for command-line scripts and small applications.
3. Use the log level constants
The static methods on Log map directly to the constants on LogLevel:
use GT\Logger\Log;
use GT\Logger\LogLevel;
Log::debug("Debug details");
Log::error("Something went wrong");
echo LogLevel::ERROR;
The constants are most useful when configuring handlers, because they help us avoid spelling mistakes.
4. Add a file handler
use GT\Logger\LogConfig;
use GT\Logger\LogHandler\FileHandler;
use GT\Logger\LogLevel;
LogConfig::addHandler(
new FileHandler("var/app.log"),
LogLevel::DEBUG
);
From this point on, every log at DEBUG and above will be appended to var/app.log.
5. Split stdout and stderr
Many applications want general output on stdout but errors on stderr.
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
);
This keeps lower-severity logs on stdout while routing ERROR, CRITICAL, ALERT, and EMERGENCY to stderr.
6. Attach context data
use GT\Logger\Log;
Log::error("Unable to save profile", [
"userId" => 42,
"section" => "preferences",
]);
The context is appended to the log line in a readable key/value format.
Next: Log levels