Logging for PHP (Monolog)

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is logging in PHP and why is it needed?

Logging is the process of recording information about an application's operation: errors, warnings, debug messages, and user actions. In PHP, unlike Python, there is no built-in PSR-compatible logger "out of the box" (although there is the error_log() function). Therefore, the best solution is to use the Monolog library — the de facto logging standard for PHP projects.

Why log?

  • Production debugging (error stack traces)
  • Performance monitoring
  • Security audit (logins, data changes)
  • User behavior analysis

Installing Monolog

Installation is done via Composer (the PHP equivalent of pip):

composer require monolog/monolog

You will need PHP 8.0+ and Composer 2.x to work.

Main functions and features

Monolog supports:

  • Channels — isolated loggers for different parts of the application (e.g., 'security', 'database')
  • Logging levels (DEBUG, INFO, WARNING, ERROR, CRITICAL, etc.)
  • Handlers — where to write: files, databases, Slack, Telegram, email
  • Processors — enriching messages with context (IP, time, session)

Code example

<?phprequire 'vendor/autoload.php';

use Monolog\\Logger;use Monolog\\Handler\\StreamHandler;use Monolog\\Handler\\TelegramBotHandler;use Monolog\\Processor\\WebProcessor;

// Create the 'app' channel$log = new Logger('app');

// Handler for writing to a file$log->pushHandler(new StreamHandler(__DIR__.'/logs/app.log', Logger::WARNING));

// Handler for Telegram (optional)$telegram = new TelegramBotHandler('YOUR_BOT_TOKEN', 'CHAT_ID', Logger::CRITICAL);$log->pushHandler($telegram);

// Processor for adding IP and User-Agent$log->pushProcessor(new WebProcessor());

// Logging$log->info('User logged into the system', ['user_id' => 123]);$log->error('Database error', ['sql' => 'SELECT * FROM users']);

When to use

Monolog is mandatory in the following cases:

  • Any commercial or open-source PHP project (Symfony, Laravel use Monolog by default)
  • Microservices and APIs — for request tracing
  • Cron scripts and workers — for tracking task execution
  • When integrating with external services (logs to Graylog, Sentry, Papertrail)

The library has been tested in thousands of projects and supports almost any log transport. If you are writing in PHP — start with Monolog.

Recommendations