Laravel. Error-prone Logging

When working with Laravel logging into a file is easy. However, when commands run under a more privileged user than the web user, permission denied errors can occur. Here is how to solve it.

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:

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

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

'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:

$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.

Previous
NetBeans Platform. How to Invoke/Call an Action Programmatically
Next
How to Install the IBM Cloud Functions on Linux Mint

Keep Reading

Explore more articles and insights

Ork: SSH Server Automation in Go

Ork: SSH Server Automation in Go

Read Article
Deno Deploy Killed My Start Page

Deno Deploy Killed My Start Page

Read Article
Back to Golang: Why I Switched From Static to Dynamic Again

Back to Golang: Why I Switched From Static to Dynamic Again

Read Article
View All Blog Posts