简体   繁体   English

每次作业运行时单独的日志文件 laravel

[英]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.我有一个 Laravel 8 应用程序,我可以在其中针对特定帐户运行我的作业。 For each account, I need a separate log file in a format such as "logFileName_122323123_2021-01-01" (logFileName__) and so on.对于每个帐户,我需要一个单独的日志文件,格式为“logFileName_122323123_2021-01-01”(logFileName__) 等。

Similar question how to customize file name of log in Laravel 8.0?类似问题如何在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.我在我的工作构造函数中尝试过,但由于我静态调用 Log,它不保留其值。

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.从 Laravel v8.66.0开始,您可以即时创建日志通道。 You can check the PR as Docs as well您也可以将PR作为文档查看

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. ManojKiran Appathurai 发布的答案是正确的,但是当我从同一个命令运行两个作业时遇到了问题。 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.现在,由于每个作业都有不同的通道,我们可以轻松地为每个作业创建单独的日志,即使它们是通过单个命令运行的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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