Laravel includes MonoLog, which is a rfc5424 compatible logging library, which basically means you log in the same way as if you were using a similar Library in another language, or even just another PHP logging library (such as Log4PHP, which I used before I started using Laravel).
Logging Levels
The key principle behind rfc5424 logging is there are 8 levels of log, they are, starting from the most serious (or severe as it is called in the RFC), progressing to the least serious:
- Emergency: system is unusable
- Alert: action must be taken immediately
- Critical: critical conditions
- Error: error conditions
- Warning: warning conditions
- Notice: normal but significant condition
- Informational: informational messages
- Debug: debug-level messages
The great thing about this degree of seperation is that you can turn on logging for all levels in development, allowing you to see exactly what is happening as your program executes, and then switch to a less in depth logging level, that will only report when something goes wrong (warning or above is usually about right, it depends where how frequent, or significant your notices are!)
How to Log
Now you’ve got the general idea, on to how to log! If you’re using Fascades, you just call the logger as so:
Log::emergency('No database available. Application unusable.');
Log::alert('Took 3 attempts to connect to database, service degraded');
Log::error('Failed to find a route for request.');
Log::warning('Something unpleasant happened!');
Log::notice('Attempted to access undefined variable, check logic');
Log::info('Successfully connected to database.');
Log::debug('Set theme to mobile');
But, if you want to avoid Fascades, then this is how you’d do it:
$app = app();
$logger = $app->make('log');
$logger->error(
'Something went wrong sending an email',
array(
'context' => $e->getMessage()
)
);
Handling What Gets Saved
In Laravel, the logging is configured in app/start/global.php, and this is the default line that we’ll be updating:
Log::useFiles(storage_path().'/logs/laravel.log');
Now, assuming you’re happy with the way that Laravel names the files, you’d just change that line to this to save only warnings, or more serious:
Log::useFiles(storage_path().'/logs/laravel.log', 'warning');
As you can see in the Laravel source , now, if we want to create daily logs, with the date in their names, we need to use useDailyFiles (which I think may have been the default in the past). Now, to use this we need to pass in the path, number of days, and the log level.
Looking at Monolog’s source “number of days” translates to “number of files to keep”, zero is unlimited, setting it to anything else will cause your logs to automatically get deleted.
So, I’ve gone with the following in my own application:
Log::useDailyFiles(storage_path().'/logs/laravel.log', 0, 'warning');
That’s all for now, but if you have any questions or suggestions feel free to drop me an email.