Logging and error-handling is built right into Laravel 5, so you do not need to build own exception handlers and logging mechanisms as with own custom projects. This is one of the many benefits of using a ready-to-go framework like Laravel 5.
Configuring Laravel logging
You can set various levels of logging, and choose which grouping you want in your log files. You can change the logging related values in the “config/app.php” file. The “debug” paramenter is set to the environment value APP_DEBUG by default, so you can set it to a general value in the config file, or change locally in the environment file. Note that debugging should always be deactivated (=false) in your production environment. The log file grouping can be set to single, daily, syslog and errorlog modes.
Showing an error with Laravel
Instead of throwing a PHP exception you can use the Laravel error method.
// Show a non-descript 404 (not found) error abort(404); // Pass a message with the 404 error abort(404, 'Invalid title'); // Show a non-descript 403 (forbidden) error abort(403); // Pass a message with the 403 error abort(403, 'You are not logged in.');
Use custom error pages
It is easy to add custom error pages to your Laravel project. Simply add them into the resources folder like other views. For example “resources/views/errors/404.blade.php”. In that file you can design the template used whenever an error with type 404 is triggered.
Add log entries
You can use the following standard logger methods to add entries to the log file.
Log::emergency($error); Log::alert($error); Log::critical($error); Log::error($error); Log::warning($error); Log::notice($error); Log::info($error); Log::debug($error);
If you need to provide further information to describe or explain the error better, then you can pass contextual information to the logger method. This data will be made available for later review and may thereby aid the debugging process significantly.
Log::info('Invalid name.', ['id' => $user->name]);
Solving errors with log files
Reviewing and reviewing the log files can sometimes be cumbersome, so therefore it may help to limit the logging messages to the really relevant information and avoid clutter. Furthermore it helps to use a good log viewer tool and keep the log file open constantly. There are programs like “Console” on Mac which can live-update the files they monitor, so any new log entry will automatically be displayed in the viewer. This speeds up the problem solving process when developing locally, so you do not have to constantly reopen the same log file (especially when debugging commands or other scripts that do not show the error on a reloadable website, you will benefit form an efficient way of monitoring and reviewing your log files).
No comments yet (leave a comment)