msstc4symfony / logger-bundle
Monolog extension
Package info
github.com/msstc4symfony/logger-bundle
Type:symfony-bundle
pkg:composer/msstc4symfony/logger-bundle
Requires
- php: >=8.2
- composer-runtime-api: >=2.2
- ext-json: *
- monolog/monolog: ^3.5
- symfony/framework-bundle: ^7.4|^8.0
- symfony/monolog-bundle: ^3.11|^4.0
- symfony/polyfill-php84: ^1.31
- symfony/security-bundle: ^7.4|^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.76
- phpstan/extension-installer: ^1.4
- phpstan/phpstan: ^2.1
- phpstan/phpstan-beberlei-assert: ^2.0
- phpstan/phpstan-strict-rules: ^2.0
- phpstan/phpstan-symfony: ^2.0
- phpunit/phpunit: >=11.5.50
- rector/rector: ^2.1
- roave/security-advisories: dev-latest
- sentry/sentry: ^4.0
- spaze/phpstan-disallowed-calls: ^v4.0
Suggests
None
Provides
None
Conflicts
Replaces
None
README
A Symfony bundle that extends Monolog with enhanced logging capabilities, including context-aware processors, flexible formatters, exception filtering, and Sentry integration.
Features
- 🔄 Smart Log Processors - Automatically enrich logs with contextual information
- 📊 Flexible Formatters - Switch between human-readable and JSON formats
- 🚫 Exception Filtering - Filter out specific exceptions from logs
- 🔗 Sentry Integration - Seamless integration with Sentry error tracking
- 🎯 Context-Aware Exceptions - Extract additional context from custom exceptions
- ⚙️ Zero Configuration - Works out of the box with sensible defaults
Requirements
- PHP 8.2 or higher (bundle 1.0 needs PHP 8.4)
- Symfony 7.4 or 8.x (Symfony 8 needs PHP 8.4)
- Monolog 3.x
sentry/sentry4.x, only for the optional Sentry integration
Installation
composer require msstc4symfony/logger-bundle
If you're using Symfony Flex, the bundle will be automatically registered. Otherwise, add it to your
config/bundles.php:
return [ // ... Msstc4Symfony\LoggerBundle\LoggerBundle::class => ['all' => true], ];
Configuration
Basic Configuration
The bundle works with minimal configuration. Set the following environment variables:
# .env
APPLICATION_NAME=my-app
COMPONENT_NAME=api
These values will be automatically added to all log entries and Sentry events.
Monolog Configuration
Add the bundle's configuration to your config/packages/monolog.yaml:
monolog: channels: - deprecation when@prod: monolog: handlers: main: type: stream path: php://stdout level: info channels: [ "!doctrine", "!event", "!deprecation" ] formatter: Msstc4Symfony\LoggerBundle\Framework\Monolog\Formatter\SwitchFormatter errors: type: stream path: php://stdout level: notice channels: [ "doctrine", "event" ] formatter: Msstc4Symfony\LoggerBundle\Framework\Monolog\Formatter\SwitchFormatter console: type: console process_psr_3_messages: false level: notice channels: [ "!deprecation" ] formatter: Msstc4Symfony\LoggerBundle\Framework\Monolog\Formatter\SwitchFormatter when@dev: monolog: handlers: main: type: stream path: php://stdout level: debug channels: [ "!doctrine", "!event", "!deprecation" ] formatter: Msstc4Symfony\LoggerBundle\Framework\Monolog\Formatter\SwitchFormatter errors: type: stream path: php://stdout level: info channels: [ "doctrine", "event" ] formatter: Msstc4Symfony\LoggerBundle\Framework\Monolog\Formatter\SwitchFormatter console: type: console process_psr_3_messages: false level: debug channels: [ "!event", "!doctrine", "!console", "!deprecation" ] formatter: Msstc4Symfony\LoggerBundle\Framework\Monolog\Formatter\SwitchFormatter
Exception Filtering
Configure which exceptions should be filtered from logs (the listed classes are the defaults;
every entry must be an existing class implementing Throwable):
# config/packages/msstc4symfony_logger.yaml msstc4symfony_logger: exception_classes: - Symfony\Component\HttpKernel\Exception\NotFoundHttpException - Symfony\Component\HttpKernel\Exception\BadRequestHttpException - Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException - Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException - Symfony\Component\Security\Core\Exception\AccessDeniedException
Sentry Integration
If you're using Sentry, add the LoggerIntegration to your Sentry configuration:
# config/packages/sentry.yaml sentry: options: integrations: - Msstc4Symfony\LoggerBundle\Framework\Sentry\Integration\LoggerIntegration
This will automatically add application and component tags to all Sentry events.
Components
Processors
The bundle includes several processors that automatically enrich log records with contextual information:
WebProcessor
Adds HTTP request information to logs:
url- Full request URLip- Client IP addresshttp_method- HTTP method (GET, POST, etc.)
UserProcessor
Adds authenticated user information:
user_id- Identifier of the authenticated user
ConsoleProcessor
Adds CLI command information:
cmd- Full command line with arguments
EnvironmentProcessor
Adds environment information:
sapi- PHP SAPI (cli, fpm-fcgi, etc.)container_id- Container/pod identifier (POD_NAME, POD_UID, or hostname)
ExceptionContextProcessor
Extracts additional context from exceptions that implement ContextAwareExceptionInterface. This allows you to attach
custom context data to your exceptions:
use Msstc4Symfony\LoggerBundle\Application\Exception\ContextAwareExceptionInterface; use Msstc4Symfony\LoggerBundle\Application\Exception\ContextAwareExceptionTrait; class PaymentFailedException extends \RuntimeException implements ContextAwareExceptionInterface { use ContextAwareExceptionTrait; public function __construct( string $message, private readonly string $transactionId, private readonly float $amount, ) { parent::__construct($message); $this->context = [ 'transaction_id' => $this->transactionId, 'amount' => $this->amount, ]; } }
Formatters
JsonFormatter
Formats log records as JSON with additional features:
-
Adds
applicationandcomponentfields -
Extracts metrics (
count,size,duration,id,status) from context into a separatemetricsfield -
Moves the
extrakeys listed injson_top_level_extrato the end of the record — with tracing-bundletrace_id,span_idandparent_span_id(null for the span of a unit of work), so a log query readstrace_idinstead ofextra_trace_idafter Loki's| json:# config/packages/msstc4symfony_logger.yaml msstc4symfony_logger: json_top_level_extra: [trace_id, span_id, parent_span_id]
{"message":"Order created","context":{},"level":200,"level_name":"INFO","channel":"app","datetime":"2026-10-22T10:00:00+00:00","extra":{"url":"/orders"},"application":"shop","component":"api","metrics":{},"trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","span_id":"00f067aa0ba902b7","parent_span_id":null}Nothing moves by default; a blank key and a key named like a field of every record (
message,context,level,level_name,channel,datetime,extra,application,component,metrics) are rejected. -
Supports structured logging for log aggregation systems
SwitchFormatter
Intelligently switches between formatters based on the environment:
- Human-readable format - When running in CLI with
HUMAN_READABLEenv var set - JSON format - For production environments and log aggregation
Example usage:
# Enable human-readable logs in CLI
HUMAN_READABLE=1 php bin/console your:command
Handlers
ExceptionFilterDecorator
A PSR-3 logger decorator that filters out specific exception types from logs. This is useful for preventing log spam from expected exceptions like 404 or validation errors.
The decorator is automatically applied to loggers based on your configuration.
Usage Examples
Basic Logging
use Psr\Log\LoggerInterface; class OrderService { public function __construct( private LoggerInterface $logger, ) {} public function processOrder(Order $order): void { $this->logger->info('Processing order', [ 'order_id' => $order->getId(), 'amount' => $order->getTotal(), ]); // The log will automatically include: // - User ID (if authenticated) // - Request URL and IP (in HTTP context) // - Container ID // - Application and component names } }
Logging with Metrics
The bundle automatically extracts common metrics from log context:
$this->logger->info('Database query executed', [ 'duration' => 0.245, // Will be extracted to metrics.duration 'count' => 42, // Will be extracted to metrics.count 'size' => 1024, // Will be extracted to metrics.size 'query' => 'SELECT * FROM users', // Remains in context ]);
This produces a structured JSON log:
{
"message": "Database query executed",
"level": "info",
"application": "my-app",
"component": "api",
"metrics": {
"duration": 0.245,
"count": 42,
"size": 1024
},
"context": {
"query": "SELECT * FROM users"
},
"extra": {
"url": "https://example.com/api/users",
"ip": "192.168.1.1",
"http_method": "GET",
"user_id": "john.doe"
}
}
Context-Aware Exceptions
Create custom exceptions with additional context:
use Msstc4Symfony\LoggerBundle\Application\Exception\ContextAwareExceptionInterface; use Msstc4Symfony\LoggerBundle\Application\Exception\ContextAwareExceptionTrait; class OrderProcessingException extends \RuntimeException implements ContextAwareExceptionInterface { use ContextAwareExceptionTrait; public function __construct( string $message, private readonly string $orderId, private readonly string $status, ) { parent::__construct($message); $this->context = [ 'order_id' => $this->orderId, 'status' => $this->status, ]; } } // When logged, the exception's context will be automatically added to the log record try { // ... } catch (OrderProcessingException $e) { $this->logger->error('Order processing failed', ['exception' => $e]); // Log will include order_id and status from the exception context }
Advanced Configuration
Custom Application and Component Names
By default both come from the APPLICATION_NAME / COMPONENT_NAME environment variables
(unknown when unset).
# config/packages/msstc4symfony_logger.yaml msstc4symfony_logger: application_name: 'my-app' component_name: 'php-fpm'
Adding More Exception Filters
exception_classes replaces the default list, so repeat the defaults you still want:
# config/packages/msstc4symfony_logger.yaml msstc4symfony_logger: exception_classes: - Symfony\Component\HttpKernel\Exception\NotFoundHttpException - App\Exception\ExpectedBusinessException - App\Exception\ValidationException
Public API
Applications use or implement only these; every other class is @internal and may change in a minor release.
| Class | Use |
|---|---|
Msstc4Symfony\LoggerBundle\Application\Exception\ContextAwareExceptionInterface, ContextAwareExceptionTrait |
exceptions that add log context |
Msstc4Symfony\LoggerBundle\Framework\Monolog\Formatter\SwitchFormatter |
formatter id in monolog.yaml |
Msstc4Symfony\LoggerBundle\Framework\Sentry\Integration\LoggerIntegration |
integration id in sentry.yaml |
Msstc4Symfony\LoggerBundle\LoggerBundle |
the bundle |
The configuration keys msstc4symfony_logger.application_name, component_name, exception_classes and
json_top_level_extra are public too.
Upgrading from 1.x: 2.0 moved every class into the canonical layers — see the CHANGELOG for the old → new names
(SwitchFormatter in monolog.yaml, LoggerIntegration in sentry.yaml). Processors, JsonFormatter and
ExceptionFilterDecorator are registered by the bundle; refer to their behaviour, not their class names.
Development
Running Tests
make test
Code Quality
make check
License
This bundle is released under the MIT License. See the LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Support
If you encounter any issues or have questions, please open an issue on GitHub.