Logging Best Practices

matt
Matthew Gros · Sep 1, 2025

TLDR

Log at appropriate levels, include context, use structured logging, centralize in production.

Logging Best Practices

Logs Help You Debug

If you do it right.

Log Levels

Log::emergency('System is down');
Log::alert('Action required immediately');
Log::critical('Critical error');
Log::error('Error occurred');
Log::warning('Something unusual');
Log::notice('Normal but significant');
Log::info('Informational');
Log::debug('Debug details');

Use appropriate levels. Not everything is an error.

Include Context

// Bad
Log::error('Payment failed');

// Good
Log::error('Payment failed', [
    'user_id' => $user->id,
    'amount' => $amount,
    'provider' => 'stripe',
    'error_code' => $e->getCode(),
]);

Structured Logging

// JSON format for log aggregators
{
    "level": "error",
    "message": "Payment failed",
    "context": {
        "user_id": 123,
        "amount": 99.99
    },
    "timestamp": "2024-01-15T10:30:00Z"
}

What to Log

Do log:

  • Errors and exceptions
  • Authentication events
  • Important business events
  • Performance metrics
  • External API calls

Don't log:

  • Passwords or tokens
  • Full credit card numbers
  • Personal data (GDPR)
  • Every request (too noisy)

Log Rotation

// config/logging.php
'daily' => [
    'driver' => 'daily',
    'path' => storage_path('logs/laravel.log'),
    'days' => 14,
],

Centralized Logging

For production, aggregate logs:

  • ELK Stack (Elasticsearch, Logstash, Kibana)
  • Papertrail
  • Loggly
  • CloudWatch Logs

Search across all servers, set up alerts.

Request IDs

Track requests across services:

$requestId = request()->header('X-Request-ID') ?? Str::uuid();
Log::withContext(['request_id' => $requestId]);

About the Author

matt

I build and ship automation-driven products using Laravel and modern frontend stacks (Vue/React), with a focus on scalability, measurable outcomes, and tight user experience. I’m based in Toronto, have 13+ years in PHP, and I also hold a pilot’s license. I enjoy working on new tech projects and generally exploring new technology.