简体   繁体   中英

Separate log files for each time a job is run laravel

I have a Laravel 8 application where I run my jobs against specific accounts. For each account, I need a separate log file in a format such as "logFileName_122323123_2021-01-01" (logFileName__) and so on.

Similar question how to customize file name of log in Laravel 8.0? but this does not help me create a new file each time I run the job.

I tried in my job constructor but since I'm calling the Log statically, it doesn't retain its value.

Config::set(['logging.channels.processPbsNormalCampaignJob.path' => storage_path('logs/processPbsNormalCampaignJob_'.$this->accountId.'_' . date('Y-m-d') . '.log')]);

What would be the best approach?

Starting from Laravel v8.66.0 you can create a log channel on the fly. You can check the PR as Docs as well

So Based on Docs you can do

Illuminate\Support\Facades\Log::build([
        'driver' => 'daily',
        'path' => storage_path('logs/processPbsNormalCampaignJob_' . $this->accountId . '_' . date('Y-m-d') . '.log'),
    ])->info('Your Log data here !!');

The answer posted by ManojKiran Appathurai is correct but I had problem when I ran two jobs from the same command. The unexpected result was that the once I built the log, I couldn't rebuild it.

What I've done now is:

Create this helper function

public function initializeLogger($fileName, $channel)
    {
        $path = 'logs/'.$fileName.'.log';
        config(['logging.channels.googlelog.path' => storage_path($path)]);

        return Log::channel($channel);
    }

Then you can create a new channel name that's specific to a job such as

'importAccountEntitiesJob' => [
            'driver' => 'daily',
            'path' => storage_path('logs/importAccountEntitiesJob.log'),
            'level' => 'debug',
            'days' => 0,
        ],

What all this is going to do is change the name of the channel dynamically. Now since we have different channels for each job, we can easily have separate logs for each job even if they're being run from a single command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM