Laravel Write Logs to Custom Files

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)

  1. Create a service provider for the custom logger. Reference
    php artisan make:provider CustomLogProvider
  2. Register that service provider in app autoloader
    In config/app.php add App\Providers\CustomLogProvider::class to ‘providers’ array.
    ‘App’ is your application name. Reference
  3. Create a custom Facade for CustomLog.
    In app folder create a new folder called Facades.
    Create a new file called CustomLog.php
    Paste the below code

    namespace 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);
        }
    }
  4. Finally, register this facade in the service provider we created earlier.
    In app/Providers/CustomLogProvider.php‘s register method add this:

    $this->app->bind('cdlog', function () {
        return new \App\Facades\ReminderMailer;
    });
  5. 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 in storage/logs folder as file1.log and file2.logYou can also use aliases for the facade created. In config/app.php add something like:
    'CustomLog' => App\Facades\CustomLog::class to aliases array.

 

Laravel Logs

References: Laravel, Monolog

I hope this helps you to take one step ahead with Laravel logging.

2 comments

Leave a Reply

Your email address will not be published. Required fields are marked *