LARAVEL

Laravel Logging with Monolog

February 4, 2024 13 min read

Introduction

Laravel leverages Monolog under the hood to provide a powerful and flexible logging system. Understanding how to configure and customize logging is essential for debugging and monitoring your applications.

Configuration

Configure logging in config/logging.php:

'default' => env('LOG_CHANNEL', 'stack'),

'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['daily', 'slack'],
    ],
    
    'daily' => [
        'driver' => 'daily',
        'path' => storage_path('logs/laravel.log'),
        'level' => 'debug',
        'days' => 14,
    ],
    
    'slack' => [
        'driver' => 'slack',
        'url' => env('LOG_SLACK_WEBHOOK_URL'),
        'username' => 'Laravel App',
        'emoji' => ':boom:',
        'level' => 'critical',
    ],
],

Logging Channels

Laravel supports multiple logging channels:

// Using different channels
Log::channel('daily')->info('Daily log message');
Log::channel('slack')->critical('Critical issue');

// Stack channel combines multiple channels
Log::stack(['daily', 'slack'])->info('Logged to multiple channels');

Custom Handlers

You can create custom Monolog handlers:

// config/logging.php
'custom' => [
    'driver' => 'monolog',
    'level' => 'debug',
    'handler' => Monolog\Handler\SyslogUdpHandler::class,
    'handler_with' => [
        'host' => 'syslog.example.com',
        'port' => 514,
    ],
],

// Custom processor
'processors' => [
    function ($record) {
        $record['extra']['user_id'] = auth()->id();
        return $record;
    },
],

Adding Context

Add contextual information to your logs:

// Basic logging
Log::info('User logged in');

// With context
Log::info('User logged in', [
    'user_id' => $user->id,
    'email' => $user->email,
    'ip' => request()->ip(),
]);

// Using Log::withContext() for request-scoped data
Log::withContext(['request_id' => $request->id]);
Log::info('Processing request');

Best Practices

  • Use Appropriate Log Levels - debug, info, warning, error, critical
  • Include Context - Add relevant data for debugging
  • Don't Log Sensitive Data - Never log passwords or tokens
  • Rotate Logs - Use daily channels with retention limits
  • Monitor Critical Logs - Send errors to alerting systems

Summary

Laravel's logging system, powered by Monolog, provides flexibility for any logging requirement. Configure multiple channels for different environments and log levels.

For more Laravel tutorials, check out our guides on Security Best Practices and Performance Optimization.