MHEMBINT
MHEMBINT

Reputation: 125

How to create multiple log files in laravel?

Like the state itself, I want to create multiple Log files for different processes. I am using Laravel-8. I have also created the 1 logging file with the help of logging.php in the config folder.

I want to keep track of my created commands with their own separate log file.

How can I create my separate log file for that commands?

I did this by having only a log for daily. "config/logging.php"

'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['daily'],
        'ignore_exceptions' => false,
    ]...,
 ]

Upvotes: 1

Views: 3853

Answers (2)

Rahmat Waisi
Rahmat Waisi

Reputation: 1330

You should use config/logging.php to create custom channel for each command e.g.

    'CHANNEL_NAME' => [
        'driver' => 'single',
        'path' => storage_path('logs/LOG_FILE_NAME.log'),
        'level' => 'DESIRED_LEVEL', 
    ],

and change CHANNEL_NAME, LOG_FILE_NAME and DESIRED_LEVEL values as you want.

Note: 'level' => 'DESIRED_LEVEL' is optional. it can be single level or array of levels (laravel v8.x).

Then when you want to log anything in your command class, Log like following code

Usage:

    Log::channel('CHANNEL_NAME')
        ->info('Something happened!');

Upvotes: 7

Rajen Trivedi
Rajen Trivedi

Reputation: 1302

Below code will generate custom log file.

try{
        //Your code here
}catch(\Exception $e){
        $cusLog = new Logger('stack');
                        $err_file_name = $task_id."_".time();
                        $syncHistory['file_name'] = $err_file_name;
                        $cusLog->pushHandler(new StreamHandler(storage_path('logs/'.$err_file_name.'.log')), Logger::INFO);
                        $cusLog->info('error', ['Exception'=>$e->getTraceAsString(),'message'=>$e->getMessage()]);
    }

Hope this will be useful.

Upvotes: 1

Related Questions