Master Monolog: Complete PHP Logging with Channels, Handlers & Processors
This guide explains Monolog's core concepts, installation, and practical usage in PHP, covering channels, handlers, formatters, processors, custom log formats, JSON output, log levels, and a comprehensive list of built‑in handlers, processors, and formatters.
Overview
Monolog is a popular PHP logging library that implements the PSR‑3 logging interface, allowing log messages to be sent to files, sockets, email, databases, and many other services.
Core Concepts
Channels : Each logger instance can have one or more named channels to differentiate log streams.
Handlers : Handlers process log records (e.g., write to a file, send email, store in a database). Multiple handlers form a stack; records pass through them in order.
Formatters : Define the output format of log records. Built‑in formatters include LineFormatter (single‑line string) and JsonFormatter (JSON).
Processors : Modify a record or add extra data (e.g., request URI, user info) before it is handled.
Installation
composer require monolog/monologBasic Usage
Create one or more logger instances, configure channels and handlers, and log messages as needed.
<?php
declare(strict_types=1);
use Monolog\Handler\FirePHPHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
require_once __DIR__ . '/vendor/autoload.php';
// ① Create a logger instance
$logger = new Logger('tinywan');
// ② Add handlers (StreamHandler writes to a file, FirePHPHandler sends to the browser console)
$logger->pushHandler(new StreamHandler('./test.log', Logger::WARNING));
$logger->pushHandler(new FirePHPHandler());
// ③ Log messages
$logger->warning('③ Add a warning log');
$logger->info('③ Add an info log'); // Not recorded because the StreamHandler level is WARNING
// ④ Add extra data using context
$logger->warning('④ Add context data', ['username' => 'Tinywan']);
// ④ Add extra data using a processor
$logger->pushProcessor(function ($record) {
$record['extra'] = [
'username' => 'Tinywan',
'age' => 24,
];
return $record;
});
$logger->warning('④ Add processor data');Using Channels
Channels let you separate logs from different parts of an application, which is useful in large projects.
use Monolog\Handler\FirePHPHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
require_once __DIR__ . '/vendor/autoload.php';
$stream = new StreamHandler('./test2.log', Logger::DEBUG);
$fire = new FirePHPHandler();
// Security channel
$securityLogger = new Logger('security');
$securityLogger->pushHandler($stream);
$securityLogger->pushHandler($fire);
$securityLogger->debug('CSRF: 1');
$securityLogger->debug('CSRF: 2');
// Payment channel
$payLogger = new Logger('pay');
$payLogger->pushHandler($stream);
$payLogger->pushHandler($fire);
$payLogger->debug('Alipay payment');
$payLogger->debug('WeChat payment');
// Clone channel for training
$trainLogger = $payLogger->withName('train');
$trainLogger->pushHandler($stream);
$trainLogger->pushHandler($fire);
$trainLogger->debug('[Clone] E‑commerce training');
$trainLogger->debug('[Clone] Live training');Custom Log Formats
You can customize the log output by configuring a formatter.
// Default date format: "Y-m-d H:i:s"
$dateFormat = "Y-m-d H:i:s";
// Default output format: "[%datetime%] %channel%.%level_name%: %message% %context% %extra%
"
$output = "[%datetime%] [%channel%] [%level_name%] %message% %context% %extra%
";
$formatter = new LineFormatter($output, $dateFormat);
$stream = new StreamHandler('./test3.log', Logger::DEBUG);
$stream->setFormatter($formatter);
$trainLogger = new Logger('train');
$trainLogger->pushHandler($stream);
$trainLogger->debug('[Clone] E‑commerce training');
$trainLogger->debug('[Clone] Live training');JSON Log Writing
// ① Create a JsonFormatter
$jsonFormatter = new JsonFormatter();
// ② Create a handler and assign the formatter
$stream = new StreamHandler('./test4.log', Logger::DEBUG);
$stream->setFormatter($jsonFormatter);
// ③ Create a logger channel
$trainLogger = new Logger('train');
$trainLogger->pushHandler($stream);
$trainLogger->debug('[Clone] E‑commerce training', [
'username' => 'Tinywan',
'age' => 24,
]);Log Levels
DEBUG (100): Detailed debugging information.
INFO (200): Meaningful events such as user login.
NOTICE (250): Normal but noteworthy events.
WARNING (300): Exceptional events that are not errors.
ERROR (400): Runtime errors that need attention.
CRITICAL (500): Critical conditions, e.g., component failure.
ALERT (550): Immediate action required, e.g., site down.
EMERGENCY (600): System unusable.
Common Handlers
StreamHandler – writes records to a PHP stream (usually a file).
SyslogHandler – writes to syslog.
ErrorLogHandler – writes to PHP error log.
NativeMailerHandler – sends logs via PHP mail().
SocketHandler – writes logs through a socket.
AmqpHandler – sends logs to an AMQP‑compatible service.
BrowserConsoleHandler – outputs logs to the browser console.
RedisHandler – stores logs in Redis.
MongoDBHandler – stores logs in MongoDB.
ElasticSearchHandler – sends logs to Elasticsearch.
BufferHandler – buffers logs for batch processing.
Common Processors
IntrospectionProcessor – adds file name, line number, class, etc.
WebProcessor – adds request URI, method, IP address.
MemoryUsageProcessor – adds current memory usage.
MemoryPeakUsageProcessor – adds peak memory usage.
Common Formatters
LineFormatter – formats a record as a single line.
HtmlFormatter – formats a record as an HTML table (useful for email).
JsonFormatter – encodes a record as JSON.
LogstashFormatter – formats a record for Logstash JSON events.
ElasticaFormatter – formats a record for Elasticsearch.
Core Concept Details
Each logger (instance of Logger) has a named channel and a stack of handlers. When a record is added, the handler stack is traversed; each handler decides whether to process the record. If a handler processes the record and its bubble flag is false, the traversal stops (similar to event bubbling).
Handlers can be shared among multiple logger instances, and formatters can be reused across handlers. Processors run before handlers and can inject additional information such as user data, request details, or custom tags.
Monolog follows the eight RFC‑5424 log levels (DEBUG, INFO, NOTICE, WARNING, ERROR, CRITICAL, ALERT, EMERGENCY) and does not support custom severity levels, though processors can add extra metadata for filtering or sorting.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
