When you create a worker application or any large application in Laravel you might want to keep track of logs. It might be necessary to save logs to different files to keep things clean. But by default the Laravel Log System doesn’t provide this feature. We can save to different files based on date, but not custom files.
But luckily there is a simple solution to achieve this using Monolog Class (which is used by Laravel for logging)
- Create a service provider for the custom logger. Reference
php artisan make:provider CustomLogProvider
- Register that service provider in app autoloader
Inconfig/app.php
addApp\Providers\CustomLogProvider::class
to ‘providers’ array.
‘App’ is your application name. Reference - Create a custom Facade for CustomLog.
Inapp
folder create a new folder calledFacades
.
Create a new file calledCustomLog.php
Paste the below codenamespace App\Facades; use Illuminate\Support\Facades\Facade; use Illuminate\Support\Facades\Log; use Monolog\Handler\StreamHandler; use Monolog\Formatter\LineFormatter; use Monolog\Logger; class CustomLog extends Facade { /** * Get Facade Accessor for Current Class * * @return string Accessor */ protected static function getFacadeAccessor() { return 'customlog'; } /** * Handle dynamic, static calls to the object. * * @param string $method * @param array $args * @return mixed */ public static function __callStatic($method, $args) { if (! isset($args[0])) { return; } $message = $args[0]; $file = isset($args[1]) ? $args[1] : 'laravel'; // Maximum number of lines in one log file $max = 10000; // Get Monolog Instance $logger = Log::getMonolog(); // Trim log file to a max length $path = storage_path('logs/'.$file.'.log'); if (! file_exists($path)) { fopen($path, "w"); } $lines = file($path); if (count($lines) >= $max) { file_put_contents($path, implode('', array_slice($lines, -$max, $max))); } // Define custom Monolog handler $handler = new StreamHandler($path, Logger::DEBUG); $handler->setFormatter(new LineFormatter(null, null, true, true)); // Set defined handler and log the message $logger->setHandlers([$handler]); $logger->$method($message); } }
- Finally, register this facade in the service provider we created earlier.
Inapp/Providers/CustomLogProvider.php
‘s register method add this:$this->app->bind('cdlog', function () { return new \App\Facades\ReminderMailer; });
- Now the Log Facade is available for use.
You can use The custom Log class like this:
App\Facades\CustomLog::info('My info log', 'file1');
Or
App\Facades\CustomLog::warning('My warning log', 'file2');
The logs are now saved instorage/logs
folder asfile1.log
andfile2.log
You can also use aliases for the facade created. Inconfig/app.php
add something like:
'CustomLog' => App\Facades\CustomLog::class
to aliases array.
I hope this helps you to take one step ahead with Laravel logging.
2 comments
This author is an inspiration.
Thank you Nithesh!!