Installation:
composer require antonchernik/logging-bundle
Ensure symfony/monolog-bundle (≥3.6) is installed (required dependency).
Register the Bundle:
Add to config/app.php under providers:
AntonChernik\LoggingBundle\LoggingBundle::class,
First Use Case:
Inject the LoggerInterface into a service/controller:
use AntonChernik\LoggingBundle\Logger\LoggerInterface;
class ExampleController
{
public function __construct(private LoggerInterface $logger)
{
}
public function index()
{
$this->logger->info('User accessed the homepage');
}
}
Configuration:
Check config/logging.php (auto-generated by Monolog) for channel setup. The bundle extends Monolog’s capabilities—verify handlers/formatters are configured.
Structured Logging:
Use named loggers for context (e.g., logger('auth')):
$this->logger->withContext(['user_id' => 123])->debug('Login attempt');
Log Levels:
Leverage all Monolog levels (emergency(), alert(), ..., debug()) with bundle-specific extensions:
$this->logger->warning('Disk space low', ['space_left' => 10]);
Custom Handlers:
Extend the bundle’s AbstractHandler to create domain-specific loggers (e.g., DatabaseHandler):
class AuditHandler extends AbstractHandler
{
protected function write(array $record): void
{
// Custom logic (e.g., store in DB)
}
}
Middleware Integration: Log requests/responses in middleware:
public function handle($request, Closure $next)
{
$this->logger->info('Request started', ['path' => $request->path()]);
$response = $next($request);
$this->logger->info('Request completed', ['status' => $response->status()]);
return $response;
}
Command Logging: Log CLI command execution:
$this->logger->command('php artisan migrate', ['exit_code' => 0]);
Laravel-Specific:
Use the Log facade as a fallback if dependency injection feels verbose:
use Illuminate\Support\Facades\Log;
Log::channel('custom')->info('Message');
(Note: Ensure the channel is configured in config/logging.php.)
Queue Workers: Log job processing:
$this->logger->job('SendEmail', ['user_id' => 123, 'status' => 'queued']);
Exception Handling:
Override render() in App\Exceptions\Handler to log errors:
public function render($request, Throwable $exception)
{
$this->logger->error($exception->getMessage(), ['trace' => $exception->getTraceAsString()]);
return parent::render($request, $exception);
}
Missing Monolog Bundle:
The package requires symfony/monolog-bundle. Install it first or face autoloading errors:
composer require symfony/monolog-bundle
Channel Configuration:
The bundle assumes Monolog channels exist. If logs disappear, verify config/logging.php:
'channels' => [
'custom' => [
'driver' => 'single',
'path' => storage_path('logs/custom.log'),
],
],
PHP 8.0+ Only: The package enforces PHP 8.0+. Downgrading will trigger autoload errors.
Logger Naming Collisions:
Avoid naming custom loggers the same as Laravel’s built-in channels (e.g., single, stack). Use unique names like app.audit.
Handler Priorities:
Handlers are processed in order. Place critical handlers (e.g., DatabaseHandler) before file handlers to avoid race conditions.
Log Not Appearing? Check:
config/logging.php.level matches the log level (e.g., debug won’t trigger an error handler).storage/logs/).Context Data Missing:
Use withContext() before logging:
// ❌ Won't work
$this->logger->info($this->logger->withContext(['key' => 'value']));
// ✅ Correct
$this->logger->withContext(['key' => 'value'])->info('Message');
Custom Handlers:
Extend AntonChernik\LoggingBundle\Handler\AbstractHandler to add logic (e.g., Slack notifications):
class SlackHandler extends AbstractHandler
{
protected function write(array $record): void
{
$this->sendToSlack($record['message'], $record['context']);
}
}
Log Formatters:
Override AntonChernik\LoggingBundle\Formatter\JsonFormatter to customize output:
class CustomJsonFormatter extends JsonFormatter
{
public function format(array $record): string
{
$record['extra']['custom_field'] = 'value';
return parent::format($record);
}
}
Service Provider Hooks:
Bind custom loggers in the bundle’s service provider (AntonChernik\LoggingBundle\LoggingBundle):
$this->app->bind('custom.logger', function ($app) {
return new CustomLogger($app['logger']);
});
Event Listeners:
Listen for log events (e.g., AntonChernik\LoggingBundle\Events\LogRecord):
public function handle(LogRecord $event)
{
if ($event->level === Logger::ERROR) {
// Trigger alert
}
}
How can I help you explore Laravel packages today?