Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Monolog Config Bundle Laravel Package

cluster28/monolog-config-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation:

    composer require cluster28/monolog-config-bundle
    

    Ensure your composer.json meets the package’s PHP/Laravel version requirements (check composer.json in the package repo).

  2. Enable the Bundle: Add the service provider to config/app.php:

    'providers' => [
        // ...
        Cluster28\MonologConfigBundle\MonologConfigBundle::class,
    ],
    
  3. Configure Monolog: Publish the default configuration:

    php artisan vendor:publish --provider="Cluster28\MonologConfigBundle\MonologConfigBundle" --tag="config"
    

    This generates a config/monolog.php file. Edit it to define your logging channels, handlers, and processors.

  4. First Use Case: Inject the Monolog service into a controller or service:

    use Psr\Log\LoggerInterface;
    
    class ExampleController extends Controller
    {
        public function __construct(private LoggerInterface $logger)
        {
            $this->logger->info('Application started');
        }
    }
    

    Verify logs appear in your configured handlers (e.g., storage/logs/laravel.log).


Implementation Patterns

Usage Patterns

  1. Centralized Logging Configuration: Use the bundle to define Monolog configurations in a single file (config/monolog.php), avoiding duplication across environments (e.g., dev, staging, prod). Example:

    return [
        'channels' => [
            'single' => [
                'handlers' => ['stream'],
            ],
            'daily' => [
                'handlers' => ['daily_file'],
                'level' => 'debug',
            ],
        ],
        'handlers' => [
            'stream' => [
                'type' => 'stream',
                'path' => storage_path('logs/laravel.log'),
                'level' => 'debug',
            ],
            'daily_file' => [
                'type' => 'rotating_file',
                'path' => storage_path('logs/laravel.log'),
                'max_files' => 30,
            ],
        ],
    ];
    
  2. Environment-Specific Logging: Override configurations per environment using Laravel’s environment files (e.g., .env). Example:

    // config/monolog.php
    'channels' => [
        'slack' => [
            'handlers' => ['slack'],
            'level' => env('LOG_LEVEL_SLACK', 'error'),
        ],
    ],
    

    Set LOG_LEVEL_SLACK=warning in .env.staging.

  3. Dynamic Handlers: Register handlers dynamically in a service provider’s boot() method:

    public function boot()
    {
        $this->app['log']->extend('sentry', function ($app) {
            return new \Sentry\Monolog\Handler(
                new \Sentry\Client($app['config']['sentry.dsn'])
            );
        });
    }
    
  4. Logging in Middleware: Use the logger in middleware to track HTTP requests:

    public function handle($request, Closure $next)
    {
        $this->logger->info('Incoming request', [
            'method' => $request->method(),
            'path' => $request->path(),
        ]);
        return $next($request);
    }
    
  5. Logging Exceptions: Override Laravel’s exception handler to log errors with Monolog:

    use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
    
    class Handler extends ExceptionHandler
    {
        public function register()
        {
            $this->renderable(function (\Throwable $e, $request) {
                $this->logger->error('Uncaught exception', [
                    'exception' => get_class($e),
                    'message' => $e->getMessage(),
                    'trace' => $e->getTraceAsString(),
                ]);
            });
        }
    }
    

Workflows

  1. Debugging Workflow:

    • Enable the debug channel in config/monolog.php for development:
      'channels' => [
          'debug' => [
              'handlers' => ['stream'],
              'level' => 'debug',
          ],
      ],
      
    • Use php artisan tinker to test logging:
      \Log::debug('Test debug message');
      
  2. Deployment Workflow:

    • Disable debug logs in production:
      'channels' => [
          'stack' => [
              'handlers' => ['single', 'daily'],
              'level' => env('APP_DEBUG') ? 'debug' : 'info',
          ],
      ],
      
    • Rotate logs post-deployment:
      php artisan config:clear
      php artisan cache:clear
      
  3. Monitoring Workflow:

    • Set up a monolog channel to forward logs to external services (e.g., Papertrail, Datadog):
      'handlers' => [
          'syslog' => [
              'type' => 'syslog',
              'identifier' => 'laravel-app',
              'facility' => LOG_USER,
          ],
      ],
      

Integration Tips

  1. Laravel Events: Log events in event listeners:

    public function handle(UserRegistered $event)
    {
        $this->logger->info('User registered', [
            'user_id' => $event->user->id,
            'email' => $event->user->email,
        ]);
    }
    
  2. Queue Jobs: Log job execution in job classes:

    public function handle()
    {
        $this->logger->info('Job started', ['job' => get_class($this)]);
        // Job logic
        $this->logger->info('Job completed');
    }
    
  3. Artisan Commands: Log command execution:

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->logger->info('Command executed', [
            'command' => $this->getName(),
            'input' => $input->all(),
        ]);
    }
    
  4. Testing: Mock the logger in PHPUnit tests:

    $logger = Mockery::mock(\Psr\Log\LoggerInterface::class);
    $this->app->instance(\Psr\Log\LoggerInterface::class, $logger);
    
    $logger->shouldReceive('info')->once()->with('Test message');
    

Gotchas and Tips

Pitfalls

  1. Configuration Overrides:

    • Pitfall: Forgetting to publish the config file (php artisan vendor:publish) will use default values, which may not match your needs.
    • Fix: Always publish and review config/monolog.php after installation.
  2. Handler Conflicts:

    • Pitfall: Duplicate handler names (e.g., stream) can cause unexpected behavior if not properly scoped.
    • Fix: Use unique handler names or namespaces (e.g., app.stream).
  3. Environment Mismatches:

    • Pitfall: Log levels or handlers defined in .env may not apply if the config file isn’t reloaded.
    • Fix: Clear config cache after changes:
      php artisan config:clear
      
  4. Performance Overhead:

    • Pitfall: Excessive logging (e.g., debug level in production) can degrade performance.
    • Fix: Use appropriate log levels and rotate files:
      'handlers' => [
          'daily' => [
              'type' => 'rotating_file',
              'path' => storage_path('logs/laravel.log'),
              'max_files' => 30,
          ],
      ],
      
  5. Circular Dependencies:

    • Pitfall: Logging services that depend on other services may cause circular references.
    • Fix: Use lazy resolution or interfaces:
      $this->app->bind(\Psr\Log\LoggerInterface::class, function ($app) {
          return new \Monolog\Logger('app', [$app['monolog.handler']]);
      });
      
  6. Alpha-Specific Issues:

    • Pitfall: Undocumented breaking changes between alpha releases.
    • Fix: Pin the package version in composer.json:
      "require": {
          "cluster28/monolog-config-bundle": "1.0.0-alpha1"
      }
      

Debugging Tips

  1. Log Not Appearing:

    • Verify the handler’s path is correct and writable:
      chmod -R 775 storage/logs/
      
    • Check for typos in channel/handler names in config/monolog.php.
  2. Handler Not Triggering:

    • Ensure the log level matches the message level (e.g., debug won’t log info messages).
    • Test with a high-priority level first:
      $this->logger->error('Test error'); // Always logs if
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle