adrenalinkin/monolog-autowire-bundle
Symfony bundle that enables autowiring of Monolog channel loggers via generated decorator classes, plus a LoggerCollection fallback mechanism. Works even without MonologBundle: missing channels fall back to the default PSR-3 logger or NullLogger.
Installation:
composer require adrenalinkin/monolog-autowire-bundle
Add to config/bundles.php:
return [
// ...
Adrenalinkin\MonologAutowireBundle\MonologAutowireBundle::class => ['all' => true],
];
First Use Case: Autowire a channel-specific logger in a service:
use Psr\Log\LoggerInterface;
class MyService
{
public function __construct(
private LoggerInterface $myChannelLogger // Autowired by bundle
) {}
}
Ensure myChannelLogger is registered in monolog config (e.g., config/packages/monolog.yaml):
monolog:
channels:
- my_channel
Define Channels:
Configure channels in monolog.yaml:
monolog:
channels:
- app
- security
- database
Autowire Loggers:
class SecurityService
{
public function __construct(
private LoggerInterface $securityLogger // Autowired
) {}
}
Fallback Handling:
Use LoggerCollection for dynamic channel resolution:
use Adrenalinkin\MonologAutowireBundle\Logger\LoggerCollection;
class DynamicLoggerService
{
public function __construct(
private LoggerCollection $loggerCollection
) {}
public function log(string $channel, string $message)
{
$logger = $this->loggerCollection->get($channel);
$logger->info($message);
}
}
monolog.yaml:
monolog:
handlers:
my_channel:
type: stream
path: "%kernel.logs_dir%/my_channel.log"
channels: [my_channel]
Missing Channels:
Autowiring a logger for an unregistered channel throws ParameterNotFoundException. Use LoggerCollection for fallback:
$logger = $loggerCollection->get('nonexistent_channel'); // Returns PSR NullLogger
MonologBundle Dependency:
The bundle works without MonologBundle, but LoggerCollection defaults to NullLogger if no channels exist.
Circular Dependencies:
Avoid circular references between services requiring the same channel logger. Use LoggerCollection to break cycles.
php bin/console debug:container | grep logger
monolog.yaml match autowired logger names (case-sensitive).Custom Logger Factories:
Override logger generation via monolog_autowire.logger_factory service:
services:
monolog_autowire.logger_factory:
class: App\Logger\CustomLoggerFactory
arguments: ['@monolog.logger']
Logger Collection Fallback:
Change the fallback logger by binding Psr\Log\LoggerInterface to a custom service.
Dynamic Channel Registration:
Register channels programmatically via Monolog\Registry:
$registry = $container->get('monolog.registry');
$registry->addLogger('dynamic_channel', $logger);
How can I help you explore Laravel packages today?