Back to Blog
Log Management for Laravel: From Chaos to Clarity
Logs Tell the Story
When things go wrong, logs are your primary debugging tool. Good logging practices make the difference between quick diagnosis and hours of frustration.
Structured Logging
// Don't
Log::info('User logged in: ' . $user->email);
// Do
Log::info('User logged in', [
'user_id' => $user->id,
'email' => $user->email,
'ip' => request()->ip(),
'user_agent' => request()->userAgent(),
]);
Log Levels
Log::emergency($message); // System is unusable
Log::alert($message); // Immediate action required
Log::critical($message); // Critical conditions
Log::error($message); // Error conditions
Log::warning($message); // Warning conditions
Log::notice($message); // Normal but significant
Log::info($message); // Informational
Log::debug($message); // Debug information
Channel Configuration
// config/logging.php
'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'),
'level' => 'error',
],
],
Contextual Logging
// Add context to all logs in a request
Log::withContext([
'request_id' => Str::uuid(),
'user_id' => auth()->id(),
]);
// Now all logs include this context
Log::info('Processing order', ['order_id' => $order->id]);
Centralized Log Management
Ship logs to a centralized system for searching and analysis:
- ELK Stack (Elasticsearch, Logstash, Kibana)
- Datadog
- Papertrail
- Logtail
Log Rotation
# /etc/logrotate.d/laravel
/var/www/app/storage/logs/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data www-data
}
Conclusion
Effective logging uses structure, appropriate levels, and centralization. Log what you'll need for debugging, ship to searchable storage, and rotate to manage disk space.
Related Articles
Need Help With Your Project?
I respond to all inquiries within 24 hours. Let's discuss how I can help build your production-ready system.
Get In Touch