Laravel. Error Prone Logging


When Laravel logs the errors thrown by your application it will write these to a log file in your storage directory: /storage/logs/laravel-2019-02-14.log

However, if you have commands in your application, it is quite usual to have the commands running under a more previleged user (i.e. admin). At the same time the web pages will be using a less privileged user (i.e. www-data). If the more privileged user do write to the log file first, the file will automatically be attributed with the more privileged user as owner. When later the less privileged user attempts to write to the same file an ugly error will be thrown.

Here is how this can be solved:

Laravel 5.7 and Above

Open your /config/logging.php file and add the following to the top:

Language: Php
$logFilename = storage_path('logs/laravel-'.php_sapi_name().'.log');

Then down the file repace the loging path with the one above:

Language: Php
'daily' => [
            'driver' => 'daily',
            'path' => $logFilename, // storage_path('logs/laravel.log'),
            'level' => 'debug',
            'days' => 14,
        ],

This will split the log file to two depending on the user: laravel-apache2handler-2019-02-14.log and laravel-cii-2019-02-14.log

Laravel 5.6 and Below

For Laravel 5.6 and below open the /bootstrap/app.php and add the following code:

Language: Php
$app->configureMonologUsing(function(Monolog\Logger $monolog) {
    $filename = storage_path('logs/laravel-'.php_sapi_name().'.log');
    $handler = new Monolog\Handler\RotatingFileHandler($filename);
    $monolog->pushHandler($handler);
});

The above will do the same as the code for Laravel 5.7 and will split the log files of the web user and the command line user.