PHP logging libraries: Monolog, Log4php, KLogger, Analog, and native logging

Compare five PHP logging options by PSR-3 support, output and maintenance. Run a Monolog JSON example and check what changes when you switch loggers.

Best practices
Illustration of log events and data analysis

After a PHP service switches loggers, the first sign of trouble can be a quiet alert. The application still calls $logger->error(), but the old query looks for the string ERROR in a field that now holds a number. Choosing a PHP logging library means choosing what writes the event and what the next system can read.

Compare the five options by what they write

Option Application interface Output and practical fit
Monolog PSR-3. Version 3.12.1 accepts psr/log 2.x or 3.x. Handlers, processors, and formatters let a framework app control destination, shared fields, and format.
Apache Log4php Its own Logger API. Hierarchical loggers, appenders and layouts, including pattern and XML. The package is abandoned and the Apache mirror is archived. Plan around it in existing apps.
KLogger PSR-3 via psr/log 1.x in 1.2.2, a 2022 release. Writes text files with configurable formatting, thresholds, and a date-based filename by default.
Analog Static API or the Analog\Logger PSR-3 wrapper. The 2023 stable tag 1.0.21 uses psr/log 3.x. Built-in or custom closure handlers determine the destination and output format.
PHP error_log() / syslog() Native functions with different arguments. Useful for scripts and runtime diagnostics when you know where the PHP or system log goes.

The Composer constraints matter. A project already using Monolog 3 with PSR-3 3.x cannot add KLogger 1.2.2 to the same dependency graph. Analog's PSR-3 wrapper may fit that API version, but you still need to choose a handler and check the emitted record. On an old Log4php service, inventory the actual appenders, thresholds and layouts before moving calls. Monolog package · KLogger package · Analog package · Apache Log4php package

Find the route your log takes today

PSR-3 gives application code a Psr\Log\LoggerInterface with eight levels and a context array. Use exception for an exception you want the logger to handle. The interface gives you a stable call site. It leaves JSON field names, storage, rotation and retention to the implementation and deployment. PHP-FIG PSR-3

In Laravel, start with the channel in config/logging.php. The logging system uses Monolog, but the channel determines the handler and format. Symfony also has minimal PSR-3 loggers, and it can use Monolog through MonologBundle. In a Symfony app, confirm the bundle is present before looking for a Monolog handler configuration. Laravel logging · Symfony logging

For a small CLI script, error_log($message) can be enough. Type 0 follows PHP's error-log configuration and its return value does not confirm delivery. Type 3 appends to the file you pass and adds no newline. syslog(LOG_ERR, $message) supplies a priority to the system logger. On a web service, check engine errors and application records separately. Their routes through the SAPI, process logs and framework handlers can differ. PHP error_log · PHP syslog · PHP error configuration

Run one event through the new formatter

In an empty test directory with PHP 8.1 or later, run composer require monolog/monolog:3.12.1. Save this CLI sample as checkout.php and run php checkout.php. The call site accepts the PSR-3 interface. The handler and formatter determine what reaches stdout.

<?php

require __DIR__ . '/vendor/autoload.php';

use Monolog\Formatter\JsonFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Psr\Log\LoggerInterface;

function reportCheckoutFailure(LoggerInterface $logger): void
{
    $logger->error('Checkout failed', [
        'event' => 'checkout_failed',
        'request_id' => 'fixture-42',
        'exception' => new RuntimeException('Synthetic failure'),
    ]);
}

$handler = new StreamHandler('php://stdout');
$handler->setFormatter(new JsonFormatter());
$logger = new Logger('checkout', [$handler]);
reportCheckoutFailure($logger);

With the pinned formatter, the sample wrote one JSON line. The numeric level was 400, the string level_name was ERROR, and the exception was nested under context.exception. datetime held the timestamp with a time zone offset. A filter on the original field name or nesting will not automatically follow these changes. Monolog JsonFormatter

Compare a normal record and an exception record from the real application before cutting over. If DataKit tails the file or container stream, inspect the fields after Pipeline parsing, then check the existing error query with both samples. Keep an application request ID distinct from a trace ID, and leave tokens and personal data out of either format. DataKit log collection

Make the destination part of the choice

A synchronous network handler can keep a PHP-FPM worker occupied while the destination responds. Writing to a local stream and forwarding from a collector moves that network hop out of the request code, while local writes can still stall under pressure. A buffer changes when the batch is sent and how much can be lost on abrupt exit. A date in a file name is not a retention policy. Match the handler to the failure behavior and disk limits the service can tolerate.

Configure Monolog · PHP logging from error_log to PSR-3

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting