Manage Laravel Logs and Error Reporting

Summary: Set up log rotation, custom error pages, and log channels.


Effective logging and error reporting are crucial for maintaining robust and reliable Laravel applications. Developers need insights into application issues, user errors, and system problems without being overwhelmed by log noise or risking sensitive data leaks. In this article, we'll explore how to manage Laravel logs with log rotation, configure custom error pages, and utilize multiple log channels for streamlined error reporting and debugging.


1. Understanding Laravel Logging

Laravel uses the Monolog PHP logging library under the hood, which enables it to support a wide variety of logging handlers, channels, and formats. By default, Laravel stores logs in the storage/logs/ directory and writes to laravel.log.

Default Log Modes:

  • single: A single log file
  • daily: A new file for each day
  • syslog: Sends logs to the system logger
  • errorlog: Sends logs to the PHP error log

You can configure the default log channel in your .env file:

LOG_CHANNEL=daily

The configuration can be further customized in config/logging.php.


2. Setting Up Log Rotation

Log rotation prevents log files from growing uncontrollably, which can consume disk space and hinder performance. Laravel's daily log channel rotates logs automatically, keeping a specified number of days' logs.

Configure the Daily Log Channel:

In .env:

LOG_CHANNEL=daily
LOG_DAYS=14

In config/logging.php:

'daily' => [
    'driver' => 'daily',
    'path' => storage_path('logs/laravel.log'),
    'level' => env('LOG_LEVEL', 'debug'),
    'days' => env('LOG_DAYS', 14),
],
  • days specifies how many daily files to retain before old logs are deleted.

Pro-tip: For multi-server deployments, consider using centralized logging services like Loggly, Papertrail, or Stackdriver.


3. Configuring Log Channels

Log channels allow you to send different types of logs to different destinations. Laravel’s stack channel lets you aggregate multiple channels.

Example Custom Channel:

Add to config/logging.php:

'custom' => [
    'driver' => 'single',
    'path' => storage_path('logs/custom.log'),
    'level' => 'info',
],

Use the Custom Channel:

Log::channel('custom')->info('This is a log entry for the custom channel.');

Stack Multiple Channels:

'channels' => [
    // ...
    'stack' => [
        'driver' => 'stack',
        'channels' => ['single', 'slack', 'custom'],
    ],
    // ...
],

Now, log messages sent to stack go to all listed channels.


4. Advanced: Logging to Slack or External Services

To get alerts on critical errors, configure integration channels like Slack:

In .env:

LOG_SLACK_WEBHOOK_URL=https://hooks.slack.com/services/your/webhook/url

In config/logging.php:

'slack' => [
    'driver' => 'slack',
    'url' => env('LOG_SLACK_WEBHOOK_URL'),
    'username' => 'Laravel Log',
    'emoji' => ':boom:',
    'level' => 'critical',
],

Now, any critical log message gets pushed to your Slack channel.


5. Custom Error Pages

By default, Laravel provides generic error pages for HTTP status codes like 404 and 500. However, custom error pages improve user experience and professionalism.

Create Custom Error Views:

Place your error views in resources/views/errors/:

  • 404.blade.php for 404 Not Found
  • 500.blade.php for 500 Internal Server Error
  • 419.blade.php for Page Expired

Example: resources/views/errors/404.blade.php

@extends('layouts.app')

@section('title', 'Page Not Found')

@section('content')
<div class="error-page">
    <h1>404</h1>
    <p>Sorry, the page you are looking for could not be found.</p>
    <a href="{{ url('/') }}">Return Home</a>
</div>
@endsection

Laravel will serve these templates automatically for the corresponding errors.


6. Handling Exceptions

For more control over logging and error display, customize app/Exceptions/Handler.php.

Example: Custom Logging for Specific Exceptions

public function report(Throwable $exception)
{
    if ($exception instanceof \App\Exceptions\CustomException) {
        Log::channel('custom')->error($exception->getMessage());
    }
    parent::report($exception);
}

Example: Custom Render Logic

public function render($request, Throwable $exception)
{
    if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
        return response()->view('errors.unauthenticated', [], 401);
    }

    return parent::render($request, $exception);
}

7. Best Practices

  • Never log sensitive information like passwords or payment data.
  • Monitor log file sizes and use rotation.
  • Limit log retention based on compliance and privacy needs.
  • Use log levels (debug, info, notice, warning, error, critical, alert, emergency) appropriately for clarity.

Conclusion

Efficient logging and error reporting in Laravel are vital for debugging and maintaining your application. Use log rotation to manage disk usage, custom log channels for better organization, and attractive error pages for a polished user experience. Explore integrations with external services for alerting, and always handle exceptions with care.

By adopting these strategies, you can ensure your Laravel project remains stable, user-friendly, and easy to maintain.


Further Reading: