Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize the log output for a job in Laravel?

I see that Laravel uses the Monolog library to handle logs. I have the following handle method in the job:

ApiUpdateItemJob.php:

public function handle()
{
    $data = [
        'id' => $this->item_id,
        'data[status]' => $this->status,
    ];

    $response = ApiFacedeClient::exec('Item', 'update', $data);

    $result = json_decode($response->getBody());
}

In the worker's log (supervisor) I see the following:

[2019-12-17 02:13:13][40770367] Processed: App\Jobs\UpdateItemStatus
[2019-12-17 05:11:53][40792760] Processing: App\Jobs\UpdateItemStatus
[2019-12-17 05:11:54][40792761] Processing: App\Jobs\UpdateItemStatus
[2019-12-17 05:11:54][40792760] Processed: App\Jobs\UpdateItemStatus
[2019-12-17 05:11:54][40792762] Processing: App\Jobs\UpdateItemStatus

What should I add to the job to see the following line:

[2019-12-17 05:11:54][40792762] Processing item id #333333 (Status [200 OK]): App\Jobs\UpdateItemStatus

like image 621
Павел Иванов Avatar asked Dec 20 '19 09:12

Павел Иванов


1 Answers

The log you see in the worker's log file is outputted by Laravel and and it is not configurable.

Your best option is to define a custom log channel which logs to the worker's file and push your after your HTTP request.

  1. Define a single file or path based logger channel config/logging.php:

    'supervisorLog' => [
        'driver' => 'single',
        'name' => 'supervisor-log',
        // ath should be same as stdout_logfile in supervisord.conf
        'path' => storage_path('path/to/supervisor/log/file'), 
        'locking' => false
    ],
    
  2. Add this after $result = json_decode($response->getBody()); in your ApiUpdateItemJob.php:

    Log::channel('supervisorLog')->info("Processing item id " + $this->item_id +" (Status ["+ $response->status() +"]): App\Jobs\UpdateItemStatus");

The result will be something like:

[2019-12-17 05:11:53][40792760] Processing: App\Jobs\UpdateItemStatus

[2019-12-17 05:11:54][40792761] Processing item id #333333 (Status [200]): App\Jobs\UpdateItemStatus

[2019-12-17 05:11:54][40792760] Processed: App\Jobs\UpdateItemStatus

like image 153
Sapnesh Naik Avatar answered Oct 13 '22 19:10

Sapnesh Naik