Andrew Cavanagh

Developer.  Project Architect.  Huge Nerd.

(not necessarily in that order)

The team I work with has a number of apps that in production use but still under heavy development. We like to have the logs on production as sparse as possible so if there is an error we don’t have to sort through piles of debug and info output to find it. On the other hand, we’re always adding new features and refining things and need to have a bunch of debug and info statements to watch the workflows and dig into different aspects of them - I usually work with the log being tailed in a console window and like to keep an eye on the processes there. Having to remove all the debug and info log statements before the code went to production was annoying. If the app was more mature and updated less often it would be one thing, but we’re deploying new stuff and updating the old stuff constantly. To that end we wanted to control the log levels that get written on a per-environment basis. We accomplished that with the following code snippet added to bootstrap/app.php:

/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
//THIS IS THE CODE SNIPPET
$app->configureMonologUsing(function ($monolog) {
    $path = storage_path() . '/logs/laravel.log';
    $logLevel = env('LOG_LEVEL', 'error'); <---THIS SETS THE MINIMUM LOG LEVEL TO WHATEVER THE LOG_LEVEL ENV VARIABLE IS, WITH A DEFAULT OF ERROR
    $monolog->pushHandler(
        $handler = new StreamHandler(
            $path,
            $logLevel
        )
    );
    $handler->setFormatter(new LineFormatter(null, null, true, true));
});
//END SNIPPET
return $app;

It’s important to note that this only works if you’re using the monolog logger, which is the default for Laravel 5.1. It uses the standard monolog log levels:

Log::emergency($error);
Log::alert($error);
Log::critical($error);
Log::error($error);
Log::warning($error);
Log::notice($error);
Log::info($error);
Log::debug($error);

It goes in order, so if you set the minimum log level to ‘warning’ you’ll get warning, error, critical, alert, and emergency messages but not notice, info, or error.


comments powered by Disqus