Master Laravel 12 Logging: Step-by-Step Guide with Code Examples
Logging is like your application’s diary—it keeps track of everything that happens, from errors to important events. In Laravel 12, logging is simple yet powerful, and this guide will walk you through everything you need to know, even if you’re just getting started. Let’s dive in!
Why Logging Matters
Logging helps you:
- Debug errors quickly
- Monitor your app’s behavior
- Track user activity
- Keep a record of critical events
Laravel 12 uses the Monolog library under the hood, but Laravel’s clean and intuitive API makes logging easy.
Default Logging Setup
By default, Laravel 12 stores logs in storage/logs/laravel.log. You can start logging immediately using the Log facade.
Writing Your First Log Message
Add the following code to a route or controller:
<?php
use Illuminate\Support\Facades\Log;
Route::get('/test-log', function () {
Log::info('This is a test log message!');
return "Check your logs!";
});
When you visit /test-log, you’ll see an entry in storage/logs/laravel.log like:
[2024-03-15 12:00:00] local.INFO: This is a test log message!
Alternative: The log Helper
Instead of importing the facade, you can use the log helper:
<?php
log()->info('Quick log message');
Both methods work the same—it’s just a matter of style!
Configuring Log Channels
Laravel 12 lets you send logs to multiple destinations (channels) such as files, Slack, or databases. Configure these in config/logging.php.
Default Configuration
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
'default' => env('LOG_CHANNEL', 'stack'),
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => env('LOG_DEPRECATIONS_TRACE', false),
],
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => env('LOG_DAILY_DAYS', 14),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => env('LOG_SLACK_USERNAME', 'Laravel Log'),
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];
Key Channels Explained
- stack: Combines multiple channels (e.g., file and Slack).
- single: Logs to a single file (
laravel.log). - daily: Rotates log files daily (keeps logs for a set number of days).
- slack: Sends critical logs to a Slack channel.
Writing Log Messages
Use the Log facade with various severity levels:
<?php
Log::emergency($message); // System is unusable
Log::alert($message); // Immediate action required
Log::critical($message); // Critical conditions
Log::error($message); // Runtime errors
Log::warning($message); // Warnings
Log::notice($message); // Normal but significant events
Log::info($message); // Informational messages
Log::debug($message); // Detailed debug information
Example: Logging User Activity
<?php
public function login(Request $request) {
// ... login logic ...
Log::info('User logged in', ['user_id' => auth()->id()]);
return redirect('/dashboard');
}
This would log an entry like:
[2024-03-15 12:05:00] local.INFO: User logged in {"user_id":1}
Contextual Logging
Add extra context to your logs using an array. For example:
<?php
try {
// Some risky code...
} catch (\Exception $e) {
Log::error('Payment failed', [
'error' => $e->getMessage(),
'user' => auth()->user()->email,
'amount' => 100,
]);
}
Logging to Different Channels
You can send logs to a specific channel using the channel() method:
<?php
// Send critical errors to Slack
Log::channel('slack')->critical('Server is down!');
// Log user signups to a custom daily channel
Log::channel('daily')->info('New user registered', ['email' => $user->email]);
Custom Log Channels
You can create your own log channel in config/logging.php. For example, to add a custom Slack channel:
<?php
'channels' => [
'custom_slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'My App Alerts',
'emoji' => ':fire:',
'level' => 'error',
],
],
Then use it like so:
Log::channel('custom_slack')->error('API connection failed!');
Logging Exceptions
Laravel automatically logs all exceptions to the default channel. You can also log exceptions manually:
<?php
try {
// Code that might fail...
} catch (\Exception $e) {
Log::error('Exception occurred', [
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
]);
}
Formatting Logs
You can customize log formats using a formatter. For example, add a JSON formatter to Slack logs:
<?php
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'formatter' => \Monolog\Formatter\JsonFormatter::class,
],
Best Practices
- Use appropriate log levels: Avoid logging debug messages in production environments.
- Add context: Include useful information (like user IDs or transaction details) to aid in debugging.
- Rotate logs: Use daily log channels instead of single log files for larger applications.
- Monitor critical channels: Set up alerts for logs with critical or emergency levels.
- Avoid sensitive data: Do not log passwords or credit card numbers.
Conclusion
Laravel 12’s logging system is flexible and easy to use, whether you're logging to a file, Slack, or a custom destination. Start by using the basic methods such as Log::info() or Log::error(), and enhance your logs with additional context and custom channels.
Happy logging! 🚀
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure & Mi...
Flask Blog CMS with Admin Dashboard — Python Source Code
A Flask-based blogging website with a built-in admin dashboard. Manage articles, images, categories, tags and featured p...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.