Try Live
Add Docs
Rankings
Pricing
Enterprise
Docs
Install
Install
Docs
Pricing
Enterprise
More...
More...
Try Live
Rankings
Add Docs
MonologBundle
https://github.com/symfony/monolog-bundle
Admin
MonologBundle provides seamless integration of the Monolog logging library into the Symfony
...
Tokens:
6,485
Snippets:
77
Trust Score:
9.5
Update:
4 weeks ago
Context
Skills
Chat
Benchmark
90.5
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# MonologBundle MonologBundle provides seamless integration of the Monolog logging library into the Symfony framework. It allows developers to configure and manage logging through Symfony's configuration system, supporting over 30 different handler types for outputting logs to files, databases, email services, cloud platforms, and messaging systems. The bundle automatically registers processors, formatters, and handles channel-based logging to separate log streams. The bundle offers extensive customization through YAML, XML, or PHP configuration, enabling fine-grained control over log levels, message formatting, and handler stacking. It supports advanced patterns like fingers-crossed handlers (buffering logs until an error occurs), filter handlers, deduplication, and sampling. Services can be automatically tagged with specific logging channels using PHP attributes, making it easy to organize logs by functional area. ## Installation and Bundle Registration Register the MonologBundle in your Symfony application kernel to enable Monolog integration. ```php // config/bundles.php return [ // ... other bundles Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true], ]; ``` ## Basic Stream Handler Configuration Configure a simple file-based logger that writes to a file with specified log level and permissions. ```yaml # config/packages/monolog.yaml monolog: handlers: main: type: stream path: '%kernel.logs_dir%/%kernel.environment%.log' level: debug bubble: true file_permission: 0644 use_locking: false ``` ## Rotating File Handler Set up automatic log rotation to manage file sizes and keep a limited number of log files. ```yaml # config/packages/monolog.yaml monolog: handlers: rotating: type: rotating_file path: '%kernel.logs_dir%/app.log' max_files: 10 level: info filename_format: '{filename}-{date}' date_format: 'Y-m-d' file_permission: 0644 ``` ## Console Handler Configuration Configure logging output to the console with different verbosity levels for CLI commands. ```yaml # config/packages/monolog.yaml monolog: handlers: console: type: console bubble: false verbosity_levels: VERBOSITY_QUIET: ERROR VERBOSITY_NORMAL: WARNING VERBOSITY_VERBOSE: NOTICE VERBOSITY_VERY_VERBOSE: INFO VERBOSITY_DEBUG: DEBUG console_formatter_options: format: "[%%datetime%%] %%start_tag%%%%message%%%%end_tag%% %%context%% %%extra%%\n" ``` ## Fingers Crossed Handler Buffer log messages and only write them when an error level is reached, providing full context for debugging. ```yaml # config/packages/monolog.yaml monolog: handlers: main: type: fingers_crossed action_level: error passthru_level: notice handler: nested buffer_size: 50 stop_buffering: true excluded_http_codes: [403, 404, { 400: ['^/api/'] }] nested: type: stream path: '%kernel.logs_dir%/%kernel.environment%.log' level: debug ``` ## Filter Handler Filter log records to only pass through specific log levels to the nested handler. ```yaml # config/packages/monolog.yaml monolog: handlers: warnings_only: type: filter accepted_levels: [warning, error] handler: filtered_stream filtered_stream: type: stream path: '%kernel.logs_dir%/warnings.log' ``` ## Buffer Handler Collect log messages in memory and flush them at the end of the request. ```yaml # config/packages/monolog.yaml monolog: handlers: buffered: type: buffer handler: slow_handler buffer_size: 100 flush_on_overflow: false level: info slow_handler: type: stream path: '%kernel.logs_dir%/buffered.log' ``` ## Group Handler Send log messages to multiple handlers simultaneously. ```yaml # config/packages/monolog.yaml monolog: handlers: grouped: type: group members: [file_handler, mail_handler] bubble: true file_handler: type: stream path: '%kernel.logs_dir%/app.log' mail_handler: type: native_mailer to_email: admin@example.com from_email: app@example.com subject: 'Application Error' level: critical ``` ## WhatFailureGroup Handler Send logs to multiple handlers, ignoring failures in individual handlers. ```yaml # config/packages/monolog.yaml monolog: handlers: resilient: type: whatfailuregroup members: [primary, backup] primary: type: stream path: '%kernel.logs_dir%/primary.log' backup: type: stream path: '%kernel.logs_dir%/backup.log' ``` ## Fallback Group Handler Try handlers in sequence until one succeeds. ```yaml # config/packages/monolog.yaml monolog: handlers: fallback: type: fallbackgroup members: [preferred, fallback_handler] preferred: type: stream path: '/var/log/app/main.log' fallback_handler: type: stream path: '%kernel.logs_dir%/fallback.log' ``` ## Deduplication Handler Suppress duplicate log messages within a time window. ```yaml # config/packages/monolog.yaml monolog: handlers: deduplicated: type: deduplication handler: dedupe_target store: '%kernel.cache_dir%/dedup_store' deduplication_level: error time: 60 dedupe_target: type: stream path: '%kernel.logs_dir%/deduplicated.log' ``` ## Sampling Handler Sample log messages to reduce volume (e.g., log only 1 in 10 messages). ```yaml # config/packages/monolog.yaml monolog: handlers: sampled: type: sampling handler: sample_target factor: 10 sample_target: type: stream path: '%kernel.logs_dir%/sampled.log' ``` ## Channel-Based Logging Configuration Direct logs from different channels to specific handlers for organized logging. ```yaml # config/packages/monolog.yaml monolog: channels: ['security', 'doctrine', 'api'] handlers: main: type: stream path: '%kernel.logs_dir%/main.log' channels: ['!security', '!doctrine'] security: type: stream path: '%kernel.logs_dir%/security.log' level: info channels: [security] doctrine: type: stream path: '%kernel.logs_dir%/doctrine.log' channels: type: inclusive elements: [doctrine] ``` ## Service Channel Assignment with PHP Attributes Use the WithMonologChannel attribute to automatically inject a channel-specific logger. ```php <?php // src/Service/PaymentService.php namespace App\Service; use Monolog\Attribute\WithMonologChannel; use Psr\Log\LoggerInterface; #[WithMonologChannel('payment')] class PaymentService { public function __construct( private LoggerInterface $logger ) {} public function processPayment(float $amount): void { $this->logger->info('Processing payment', ['amount' => $amount]); try { // Process payment logic $this->logger->info('Payment processed successfully'); } catch (\Exception $e) { $this->logger->error('Payment failed', [ 'exception' => $e->getMessage(), 'amount' => $amount ]); throw $e; } } } ``` ## Manual Channel Assignment with Service Tags Configure services to use specific logging channels via service tags. ```yaml # config/services.yaml services: App\Service\SecurityService: tags: - { name: monolog.logger, channel: security } App\Service\ApiService: tags: - { name: monolog.logger, channel: api } ``` ## Custom Processor with AsMonologProcessor Attribute Create custom processors to add extra data to log records using PHP attributes. ```php <?php // src/Monolog/Processor/RequestIdProcessor.php namespace App\Monolog\Processor; use Monolog\Attribute\AsMonologProcessor; use Monolog\LogRecord; use Symfony\Component\HttpFoundation\RequestStack; #[AsMonologProcessor] class RequestIdProcessor { public function __construct( private RequestStack $requestStack ) {} public function __invoke(LogRecord $record): LogRecord { $request = $this->requestStack->getCurrentRequest(); if ($request) { $record->extra['request_id'] = $request->headers->get('X-Request-Id', uniqid()); $record->extra['client_ip'] = $request->getClientIp(); } return $record; } } ``` ## Processor for Specific Handler Register a processor that only applies to a specific handler. ```php <?php // src/Monolog/Processor/SlackProcessor.php namespace App\Monolog\Processor; use Monolog\Attribute\AsMonologProcessor; use Monolog\LogRecord; #[AsMonologProcessor(handler: 'slack')] class SlackProcessor { public function __invoke(LogRecord $record): LogRecord { $record->extra['environment'] = $_ENV['APP_ENV'] ?? 'unknown'; $record->extra['server'] = gethostname(); return $record; } } ``` ## Processor for Specific Channel Create a processor that only applies to logs from a specific channel. ```php <?php // src/Monolog/Processor/SecurityProcessor.php namespace App\Monolog\Processor; use Monolog\Attribute\AsMonologProcessor; use Monolog\LogRecord; use Symfony\Bundle\SecurityBundle\Security; #[AsMonologProcessor(channel: 'security')] class SecurityProcessor { public function __construct( private Security $security ) {} public function __invoke(LogRecord $record): LogRecord { $user = $this->security->getUser(); if ($user) { $record->extra['user_id'] = $user->getUserIdentifier(); $record->extra['roles'] = $user->getRoles(); } return $record; } } ``` ## Syslog Handler Configuration Send logs to the system syslog daemon. ```yaml # config/packages/monolog.yaml monolog: handlers: syslog: type: syslog ident: symfony_app facility: local6 level: warning logopts: 1 # LOG_PID ``` ## Syslog UDP Handler Send logs to a remote syslog server over UDP. ```yaml # config/packages/monolog.yaml monolog: handlers: remote_syslog: type: syslogudp host: 'logs.example.com' port: 514 facility: local0 level: info ident: myapp ``` ## Native Mailer Handler Send critical log messages via email using PHP's native mail function. ```yaml # config/packages/monolog.yaml monolog: handlers: mail: type: native_mailer to_email: ['admin@example.com', 'devops@example.com'] from_email: 'app@example.com' subject: '[ALERT] Application Error' level: critical headers: - 'X-Priority: 1' - 'X-Mailer: Monolog' ``` ## Symfony Mailer Handler Send log messages using Symfony Mailer component. ```yaml # config/packages/monolog.yaml monolog: handlers: symfony_mail: type: symfony_mailer from_email: 'noreply@example.com' to_email: 'admin@example.com' subject: 'Application Error Report' level: error mailer: mailer.mailer # optional, service id ``` ## Slack Handler Send log messages to a Slack channel using the Slack API. ```yaml # config/packages/monolog.yaml monolog: handlers: slack: type: slack token: '%env(SLACK_API_TOKEN)%' channel: '#alerts' bot_name: 'MonologBot' icon_emoji: ':warning:' use_attachment: true use_short_attachment: false include_extra: true level: critical exclude_fields: ['context.password', 'extra.sensitive'] ``` ## Slack Webhook Handler Send log messages to Slack using an incoming webhook URL. ```yaml # config/packages/monolog.yaml monolog: handlers: slack_webhook: type: slackwebhook webhook_url: '%env(SLACK_WEBHOOK_URL)%' channel: '#monitoring' bot_name: 'AppMonitor' icon_emoji: ':robot_face:' use_attachment: true include_extra: true level: error ``` ## Telegram Handler Send log messages to a Telegram chat or channel. ```yaml # config/packages/monolog.yaml monolog: handlers: telegram: type: telegram token: '%env(TELEGRAM_BOT_TOKEN)%' channel: '%env(TELEGRAM_CHAT_ID)%' level: critical parse_mode: 'HTML' disable_webpage_preview: true disable_notification: false split_long_messages: true delay_between_messages: true topic: 123 # optional, for forum supergroups ``` ## MongoDB Handler Store log messages in a MongoDB database. ```yaml # config/packages/monolog.yaml monolog: handlers: mongodb: type: mongodb mongodb: uri: '%env(MONGODB_URL)%' username: '%env(MONGODB_USER)%' password: '%env(MONGODB_PASSWORD)%' database: logs collection: application_logs level: info ``` ## Elasticsearch Handler Send logs to Elasticsearch for centralized log management. ```yaml # config/packages/monolog.yaml monolog: handlers: elasticsearch: type: elastic_search elasticsearch: host: 'https://localhost:9200' user: elastic password: '%env(ELASTICSEARCH_PASSWORD)%' index: app-logs level: debug ``` ## Elastica Handler Use the Elastica library to send logs to Elasticsearch. ```yaml # config/packages/monolog.yaml monolog: handlers: elastica: type: elastica elasticsearch: hosts: - 'elasticsearch-node1:9200' - 'elasticsearch-node2:9200' transport: Http user: elastic password: '%env(ELASTIC_PASSWORD)%' index: symfony-logs level: info ``` ## Redis Handler Store log messages in Redis. ```yaml # config/packages/monolog.yaml monolog: handlers: redis: type: redis redis: host: '%env(REDIS_HOST)%' port: 6379 password: '%env(REDIS_PASSWORD)%' database: 1 key_name: app_logs level: warning ``` ## Predis Handler Use Predis client to store logs in Redis. ```yaml # config/packages/monolog.yaml monolog: handlers: predis: type: predis redis: host: 'tcp://redis.example.com:6379' key_name: 'monolog:logs' level: info ``` ## GELF Handler Send logs to Graylog using the GELF protocol. ```yaml # config/packages/monolog.yaml monolog: handlers: gelf: type: gelf publisher: hostname: 'graylog.example.com' port: 12201 chunk_size: 1420 encoder: compressed_json level: info ``` ## Loggly Handler Send logs to Loggly cloud logging service. ```yaml # config/packages/monolog.yaml monolog: handlers: loggly: type: loggly token: '%env(LOGGLY_TOKEN)%' level: info tags: ['symfony', 'production', 'api'] ``` ## InsightOps Handler Send logs to InsightOps (formerly Logentries). ```yaml # config/packages/monolog.yaml monolog: handlers: insightops: type: insightops token: '%env(INSIGHTOPS_TOKEN)%' region: us # or 'eu' use_ssl: true level: info ``` ## New Relic Handler Send log metadata to New Relic APM. ```yaml # config/packages/monolog.yaml monolog: handlers: newrelic: type: newrelic level: error app_name: 'My Symfony App' ``` ## Rollbar Handler Send errors and logs to Rollbar error tracking service. ```yaml # config/packages/monolog.yaml monolog: handlers: rollbar: type: rollbar token: '%env(ROLLBAR_TOKEN)%' level: error config: environment: '%kernel.environment%' code_version: '%env(APP_VERSION)%' ``` ## Socket Handler Send logs to a socket connection. ```yaml # config/packages/monolog.yaml monolog: handlers: socket: type: socket connection_string: 'tcp://logstash.example.com:5000' timeout: 30.0 connection_timeout: 5.0 persistent: true level: info ``` ## Pushover Handler Send push notifications for critical logs using Pushover. ```yaml # config/packages/monolog.yaml monolog: handlers: pushover: type: pushover token: '%env(PUSHOVER_APP_TOKEN)%' user: '%env(PUSHOVER_USER_KEY)%' title: 'Critical Alert' level: critical timeout: 10.0 ``` ## AMQP Handler Send logs to a RabbitMQ or other AMQP broker. ```yaml # config/packages/monolog.yaml services: app.amqp_exchange: class: AMQPExchange # ... AMQP exchange configuration monolog: handlers: amqp: type: amqp exchange: app.amqp_exchange exchange_name: logs level: info ``` ## Error Log Handler Send logs to PHP's error_log function. ```yaml # config/packages/monolog.yaml monolog: handlers: errorlog: type: error_log message_type: 0 # 0 = system log, 4 = SAPI handler level: warning ``` ## Custom Formatter Configuration Apply a custom formatter to a handler. ```yaml # config/packages/monolog.yaml services: app.json_formatter: class: Monolog\Formatter\JsonFormatter arguments: $batchMode: 1 # JSON_BATCH_MODE_JSON $appendNewline: true monolog: handlers: json_logs: type: stream path: '%kernel.logs_dir%/app.json.log' level: info formatter: app.json_formatter ``` ## Using Built-in Formatters Reference pre-configured formatters provided by the bundle. ```yaml # config/packages/monolog.yaml monolog: handlers: json_handler: type: stream path: '%kernel.logs_dir%/json.log' formatter: monolog.formatter.json logstash_handler: type: stream path: '%kernel.logs_dir%/logstash.log' formatter: monolog.formatter.logstash html_handler: type: stream path: '%kernel.logs_dir%/app.html' formatter: monolog.formatter.html ``` ## Include Stack Traces in Logs Configure handlers to include full stack traces for exceptions. ```yaml # config/packages/monolog.yaml monolog: handlers: main: type: stream path: '%kernel.logs_dir%/%kernel.environment%.log' level: debug include_stacktraces: true base_path: '%kernel.project_dir%' ``` ## Handler Priority Configuration Control the order in which handlers receive log records. ```yaml # config/packages/monolog.yaml monolog: handlers: # Higher priority handlers receive logs first critical_alerts: type: slack token: '%env(SLACK_TOKEN)%' channel: '#critical' level: critical priority: 100 main: type: stream path: '%kernel.logs_dir%/app.log' priority: 0 debug: type: stream path: '%kernel.logs_dir%/debug.log' level: debug priority: -100 ``` ## Conditional Handler Enabling Enable or disable handlers based on environment or conditions. ```yaml # config/packages/monolog.yaml monolog: handlers: main: type: stream path: '%kernel.logs_dir%/%kernel.environment%.log' enabled: true debug_toolbar: type: stream path: '%kernel.logs_dir%/debug.log' enabled: '%env(bool:ENABLE_DEBUG_LOGS)%' ``` ## Nested Handler Configuration Mark handlers as nested to prevent them from being added to the main stack. ```yaml # config/packages/monolog.yaml monolog: handlers: fingers_crossed: type: fingers_crossed action_level: error handler: grouped grouped: type: group members: [stream, slack] nested: true stream: type: stream path: '%kernel.logs_dir%/error.log' nested: true slack: type: slackwebhook webhook_url: '%env(SLACK_WEBHOOK)%' nested: true ``` ## PSR-3 Message Processing Configuration Configure how PSR-3 placeholder messages are processed. ```yaml # config/packages/monolog.yaml monolog: handlers: main: type: stream path: '%kernel.logs_dir%/app.log' process_psr_3_messages: enabled: true date_format: 'Y-m-d H:i:s' remove_used_context_fields: true ``` ## Service Handler Use a custom service as a handler. ```yaml # config/services.yaml services: App\Logging\CustomHandler: arguments: - '%kernel.logs_dir%/custom.log' # config/packages/monolog.yaml monolog: handlers: custom: type: service id: App\Logging\CustomHandler ``` ## Complete Production Configuration Example A comprehensive production-ready logging configuration with multiple handlers. ```yaml # config/packages/prod/monolog.yaml monolog: channels: ['deprecation', 'security', 'doctrine', 'mailer', 'api'] handlers: # Main handler with fingers crossed for production main: type: fingers_crossed action_level: error handler: grouped excluded_http_codes: [404, 405] buffer_size: 50 grouped: type: group members: [stream, deduplicated_slack] nested: true stream: type: rotating_file path: '%kernel.logs_dir%/%kernel.environment%.log' max_files: 14 level: info nested: true deduplicated_slack: type: deduplication handler: slack time: 300 nested: true slack: type: slackwebhook webhook_url: '%env(SLACK_WEBHOOK_URL)%' channel: '#alerts' level: critical nested: true # Console logging console: type: console channels: ['!doctrine'] verbosity_levels: VERBOSITY_QUIET: ERROR VERBOSITY_NORMAL: WARNING VERBOSITY_VERBOSE: NOTICE # Deprecation logging deprecation: type: rotating_file path: '%kernel.logs_dir%/deprecation.log' max_files: 7 channels: [deprecation] # Security audit log security: type: stream path: '%kernel.logs_dir%/security.log' level: info channels: [security] ``` MonologBundle is essential for building robust, production-ready Symfony applications with comprehensive logging capabilities. Its extensive handler support enables logs to be routed to virtually any destination, from simple files to sophisticated cloud-based log aggregation services. The channel system allows fine-grained control over which logs go where, enabling separate audit trails, security logs, and application debug information. The bundle integrates seamlessly with Symfony's dependency injection container, allowing services to automatically receive channel-specific loggers through PHP 8 attributes or service tags. Custom processors can enrich log records with additional context like request IDs, user information, or environment details. With support for advanced patterns like fingers-crossed buffering, deduplication, sampling, and fallback groups, MonologBundle provides all the tools needed for sophisticated logging strategies in applications of any scale.