Task Scheduling Logs with OctoberCMS

- 1 answer


I'm using OctoberCMS based on Laravel.

I have records in a database table vendor_log_.

Each day I need Laravel to save a list of the newly created records to a dated .log file.

In my Custom Component's Plugin.php file I created a registerSchedule function. I have it get() the records in the table by current date, then use file_put_contents to append them to a .log file.

However, no log file is being saved to my logs server path. I cannot tell if the schedule is not firing or what it could be, there are no errors.

public function registerSchedule($schedule)
    # Generate Daily Log File
    $schedule->call(function () {

        # Get Today's Date
        $date = date("Y-m-d");

        # Get Records by Today's Date
        # Match Record created_at date, exclude time
        $records = \Db::table('vendor_log_')
                    ->whereDay('created_at', date('d'))
                    ->whereMonth('created_at', date('m'))
                    ->whereYear('created_at', date('Y'))

        # Write records to log file
        foreach ($records as $line) {
          file_put_contents("/var/www/mysite/logs/$date.log", $line . PHP_EOL, FILE_APPEND);


Output of $line:

stdClass Object ( [user_id] => 1 [id] => 28 [username] => [name] => test [created_at] => 2017-03-22 02:39:13 )

Note: I have used ->everyMinute() in place of ->daily() to generate the logs quicker for testing.





A summary of the problem and the comments:

The problem consisted of two parts;

  • The location where the log is saved isn't writable by the user
  • The object returned by the DB class can't be written as a string

The first problem was solved by writing the log files to the public folder of the hosting that is used.

To write the DB object to a string could be done by the following code

foreach($records as $record) {
    $array = (array) $record;

    $string = '';

    foreach($record as $key => $value) {
        $string .= $key .' '. $value . ',';

    // strip the trailing comma of the end of the string
    $line = rtrim($string, ',');

    file_put_contents("/link/to/public/$date.log", $line . PHP_EOL, FILE_APPEND);
source: stackoverflow.com