The `symfony/monolog-bundle` is a crucial component that integrates the popular Monolog logging library into Symfony applications. Monolog itself is a powerful and flexible PHP logging solution that allows developers to send logs to various handlers (files, databases, emails, external services like Sentry or Slack, and more).
Purpose of the Bundle:
While Monolog provides the core logging functionality, `symfony/monolog-bundle` acts as the bridge that seamlessly integrates it into Symfony's ecosystem. It leverages Symfony's Dependency Injection container and configuration system to simplify the setup and usage of Monolog within your application.
Key Features and Benefits:
1. Centralized Configuration: All logging configurations (channels, handlers, processors) are managed through Symfony's `config/packages/monolog.yaml` file, providing a single, consistent place for logging setup.
2. Multiple Handlers: The bundle allows you to easily configure various Monolog handlers, enabling logs to be directed to different destinations based on their severity or channel. Examples include `stream` (to files), `syslog`, `console`, `native_mailer` (for email), `doctrine` (for database logging), and many third-party integrations.
3. Processors: You can attach processors to your loggers to add extra contextual data to log records, such as current memory usage, request IDs, user information, or server details. This enriches your logs and aids in debugging.
4. Channels: The bundle supports Monolog's concept of channels, allowing you to categorize logs by different application areas (e.g., `app`, `doctrine`, `security`, `request`). This makes it easier to filter and manage logs from distinct parts of your application.
5. Service Integration: The bundle registers a default `logger` service (implementing `Psr\Log\LoggerInterface`) in Symfony's Dependency Injection container. This makes it incredibly easy to inject the logger into any service, controller, or command where logging is needed, promoting consistency and testability.
6. Environment-Specific Logging: Configurations can be tailored per environment (e.g., more verbose logging in `dev`, critical errors only in `prod`), using Symfony's environment-aware configuration capabilities.
How it works:
When your Symfony application starts, the `symfony/monolog-bundle` reads your `monolog.yaml` configuration. It then constructs Monolog `Logger` instances, attaching the specified handlers and processors. These configured loggers are then made available as services in the Dependency Injection container. When you inject `Psr\Log\LoggerInterface` (or a specific channel's logger) into your code, Symfony provides the appropriate Monolog logger instance, ready for use.
Example Code
```php
// 1. Configuration: config/packages/monolog.yaml
// This configures two handlers: one for general application logs and one for critical errors via email.
monolog:
handlers:
main:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: info
channels: ["!event"]
console:
type: console
process_psr_3_messages: false
channels: ["!event", "!doctrine", "!php"]
critical_email:
type: native_mailer
from_email: "noreply@example.com"
to_email: "admin@example.com"
subject: "A Critical Error Occurred!"
level: critical
formatter: monolog.formatter.html
# You might want to enable this only in production or a specific environment
# enabled: "%kernel.environment% == 'prod'"
// 2. Usage in a Symfony Controller (src/Controller/LoggingExampleController.php)
namespace App\Controller;
use Psr\Log\LoggerInterface; // Import the PSR-3 Logger Interface
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class LoggingExampleController extends AbstractController
{
#[Route('/log-test', name: 'app_log_test')]
public function index(LoggerInterface $logger): Response
{
// Log an informational message
$logger->info('User visited the log test page.', [
'user_id' => $this->getUser() ? $this->getUser()->getId() : 'anonymous',
'ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'unknown'
]);
// Log a warning message
$logger->warning('A potential issue detected during data processing.', [
'data_id' => 12345,
'status' => 'pending'
]);
try {
// Simulate an error that might occur
throw new \Exception('This is a simulated error for logging.');
} catch (\Exception $e) {
// Log an error message with the exception details
$logger->error('An error occurred during a critical operation.', [
'exception' => $e,
'code' => $e->getCode(),
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine()
]);
// You can also log a critical message, which might trigger email notifications
$logger->critical('Application received a critical exception!', [
'exception_message' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
}
// You can also get a specific channel logger if defined in monolog.yaml
// Example: If you configured a 'security' channel
// $securityLogger = $this->container->get('monolog.logger.security');
// $securityLogger->notice('User failed login attempt.', ['username' => 'bad_user']);
$this->addFlash('success', 'Logged various messages. Check your log files and potentially your email!');
return $this->render('logging_example/index.html.twig', [
'controller_name' => 'LoggingExampleController',
]);
}
}
// 3. Example Twig Template (templates/logging_example/index.html.twig - optional for context)
{#
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Logging Example</title>
</head>
<body>
<h1>Logging Example Page</h1>
{% for message in app.flashes('success') %}
<div class="alert alert-success">{{ message }}</div>
{% endfor %}
<p>Check your `var/log/dev.log` (or `prod.log`) file for logged messages.</p>
<p>If you set up critical email, check your inbox if a critical error was triggered.</p>
</body>
</html>
#}
// After running this, check your `var/log/dev.log` (or `prod.log`) file. You will see the logged messages there.
// If a 'critical' log level was reached and the `critical_email` handler was enabled, an email would also be sent.
```








symfony/monolog-bundle