Logging in PHP Applications: Best Practices and Tools

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

Logging in PHP Applications: Best Practices



Logging is not just about writing errors to a file. It is a systematic process of collecting, storing, and analyzing information about application operation. In PHP development, properly configured logging helps quickly find bugs, track anomalies in user behavior, and ensure security auditing. In this article, we will cover best practices for logging in PHP, from standards to advanced tools.



1. Why logging is needed and basic principles



Logging solves several key tasks:

  • Debugging — recording the application state at the moment of an error.
  • Monitoring — tracking performance and load.
  • Security — recording suspicious actions (hacking attempts, unauthorized access).
  • Auditing — documenting critical business operations.


Basic principles of good logging:

  • Don't lie — logs should reflect the real state of the system.
  • Structured — use a single format (JSON, key=value).
  • Severity levels — separate debug, info, warning, error, critical.
  • No secrets — never write passwords, tokens, or personal data.


2. PSR-3 standard and LoggerInterface



PHP-FIG recommends using PSR-3 — a standard interface for logging libraries. It defines 8 levels (from debug to emergency) and a unified contract.



Example implementation using PSR-3:



<?phpuse Psr\\Log\\AbstractLogger;

class SimpleLogger extends AbstractLogger{ public function log($level, $message, array $context = []) { $logEntry = sprintf( '[%s] %s: %s %s', date('Y-m-d H:i:s'), strtoupper($level), $message, json_encode($context) ); file_put_contents('/var/log/app.log', $logEntry . PHP_EOL, FILE_APPEND); }}

$logger = new SimpleLogger();$logger->info('User registered', ['user_id' => 42]);?>


Using PSR-3 allows you to easily replace the logger library (e.g., from Monolog to your own implementation) without changing the application code.



3. Monolog — a powerful logging tool



Monolog is the most popular logging library for PHP (install via Composer: composer require monolog/monolog). It supports many handlers and formatters.



Basic Monolog setup



<?phpuse Monolog\\Logger;use Monolog\\Handler\\StreamHandler;use Monolog\\Handler\\FirePHPHandler;use Monolog\\Formatter\\LineFormatter;

$logger = new Logger('my_app');

// Handler for file$fileHandler = new StreamHandler(__DIR__ . '/logs/app.log', Logger::WARNING);$fileHandler->setFormatter(new LineFormatter("[%datetime%] %level_name%: %message% %context%"));$logger->pushHandler($fileHandler);

// Handler for browser (FirePHP)$logger->pushHandler(new FirePHPHandler());

// Usage$logger->warning('Insufficient access rights', ['user' => 'guest']);$logger->error('Database connection error', ['db_host' => 'localhost']);?>


Advanced Monolog features

  • FingersCrossedHandler — buffers logs and writes only when a certain level is reached (saves space).
  • GroupHandler — sends logs to multiple channels at once (file + Email + Slack).
  • Processors — add context (IP address, session ID, execution time).


Example with a processor for adding IP:

Blogs

Book Recommendations