Laravel Cron Job Monitoring

When we build applications using Laravel, we also have lots of Laravel cron jobs. Once the application is deployed on production server, it’s mandatory to monitor cron jobs. Many time it happens that due to certain issues crons are not executed. That may lead to lot of problems with your customers. As a server admin we can always login to server and check the logs. But what if we have a very simple page where we can see this logs.

Laravel Cron Jobs

Laravel Cron Jobs

Here in this blog I am going to explain a very simple approach to monitoring cron jobs. First of all for each cron jobs we will build a log file.

Build Laravel Cron Log File

We will use Laravel File class to create log files. First of all add to controller.

use File;

Add a variable to have counts of processed records with cron.

$count = 0;

Now inside foreach loop or any other loop you have increase this count.

foreach($records as $record){

$count++;

}

Once the cron execution logic is over build log file.

//Preparing log files on server.
$data = json_encode([“description”=>”Cron Execution Report”,”count”=>$count,”date”=>date(‘Y-m-d H:i:s’)]);
$fileName = ‘cronExecutionReport.json’;
File::put(public_path(‘/logs/’.$fileName),$data);

This way add logs files everywhere in your cron.

Read The Log File and Display It

Now that we have all the log files generated, we just have to read it and display it. Here is the logic for the same.

foreach (glob(public_path(“logs/*.json”)) as $file) {

$json = json_decode(file_get_contents($file), true);

echo ‘<span style=”font-weight:bold;font-size:25px”>’.$json[‘description’].'<br/>’;

print( ‘<span style=”font-weight:normal;font-size:20px”>Total Count : ‘.$json[‘count’].'<br/>’);

print( ‘<span style=”font-weight:normal;font-size:20px”>Last Processed Date : ‘.$json[‘date’].'<br/>’);

}
echo ‘<script type=”text/javascript”>setInterval(function(){window.location.reload()},10000)</script>’;

Add the above code in your controller function so that it will display following output and it will also refresh the page after 10 seconds to get the latest logs from server.

Cron Execution Report
Total Count : 10
Last Processed Date : 2018-11-09 10:56:01

So this way you can build a very simple Laravel Cron Job monitoring page.

Leave a Reply

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