Error&Log
1. Introduction
Larave has configured error and exception handling for us by default App\Exceptions\Handler
Class and return the response to the user. In this tutorial, we will explore this class in depth.
In addition, Larravel also integrates Monolog The log library provides various powerful log processors. By default, Larvel has configured some processors for us. We can select a single log file or record error information to the system log.
2. Configuration
Error details display
configuration file config/app.php
In debug
Configuration items control the number of error messages displayed by the browser. By default, this configuration item passes the .env
Environment variables in the file APP_DEBUG
Make settings.
For local development, you should set environment variables APP_DEBUG
Value is true
。 In the production environment, this value should be set to false
。 If it is set to true
, it is possible to expose some sensitive configuration values to the end user.
Log storage
By default, Larave supports logging methods single
, daily
, syslog
and errorlog
。 If you want to generate log files by day instead of generating and recording them to a single file, you should config/app.php
Set in log
The values are as follows:
'log' => 'daily'
Maximum life cycle of log file
use daily
In the log mode, Larravel keeps logs for the last 5 days at most by default. If you want to modify this time, you need to add a configuration log_max_files
reach app
Profile:
'log_max_files' => 30
Log error level
When using Monolog, log messages may have different error levels. By default, Larvel writes all logs to storage
Directory, but in the production environment, you may want to configure the minimum error level. This can be done by app.php
Add configuration item in log_level
To achieve.
After the configuration item is configured, Larvel will record all logs with error levels greater than or equal to the specified level. For example, by default log_level
yes error
, will record error
、 critical
、 alert
as well as emergency
Level log information:
'log_level' => env('APP_LOG_LEVEL', 'error'),
Note: Monolog supports the following error levels—— debug
、 info
、 notice
、 warning
、 error
、 critical
、 alert
、 emergency
。
Customize Monolog Configuration
If you want to fully control the configuration of Monolog in the application, you can use configureMonologUsing
method. You need to bootstrap/app.php
File Return $app
Call this method before variable:
$app->configureMonologUsing(function($monolog) { $monolog->pushHandler(...); }); return $app;
3. Exception handler
All exceptions are defined by the class App\Exceptions\Handler
Processing. This class contains two methods: report
and render
。 Let's elaborate on these two methods.
Report method
report
Method is used to record exceptions and send them to external services such as Bugsnag or Sentry , by default, report
The method just passes the exception to the base class where the exception is recorded. Of course, you can also record the exception and handle it according to your own needs.
For example, if you need to report different types of exceptions in different ways, you can use PHP's instanceof
Comparison operator:
/** *Report or record exceptions * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $e * @return void * @translator laravelacademy.org */ public function report(Exception $e){ if ($e instanceof CustomException) { // } return parent::report($e); }
Ignore exceptions by type
Exception handler's $dontReport
The property contains an array of exception types that will not be recorded. By default, 404 error exceptions will not be written to the log file. If necessary, you can add other exception types to this array:
/** *List of exception types that should not be reported * * @var array */ protected $dontReport = [ \Illuminate\Auth\AuthenticationException::class, \Illuminate\Auth\Access\AuthorizationException::class, \Symfony\Component\HttpKernel\Exception\HttpException::class, \Illuminate\Database\Eloquent\ModelNotFoundException::class, \Illuminate\Validation\ValidationException::class, ];
Render method
render
Method is responsible for converting the given exception into an HTTP response sent to the browser. By default, the exception is passed to the base class that generates the response for you. Of course, you can also check the exception type or return a custom response according to your needs:
/** *Render exceptions to HTTP responses * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, Exception $e){ if ($e instanceof CustomException) { return response()->view('errors.custom', [], 500); } return parent::render($request, $e); }
4. HTTP exception
Some exceptions describe the HTTP error code from the server. For example, this may be a "page not found" error (404), "authentication failure error" (401), or a 500 error caused by a program error. To generate such a response in the application, you can use abort
Auxiliary function:
abort(404);
abort
The auxiliary function will immediately throw an exception that will be rendered by the exception handler. In addition, you can also provide a response description like this:
abort(403, 'Unauthorized action.');
This method can be used at any point in the request lifecycle.
Custom HTTP error page
In Larravel, it is easy to return error pages with different HTTP status codes. For example, if you want to customize the 404 error page, create a resources/views/errors/404.blade.php
File, which is used for all 404 errors returned by the renderer. Note that the view naming in this directory should match the corresponding HTTP status code. abort
Function triggered HttpException
The exception will be $exception
Variables are passed to the view. 5. Log
Larave is based on the powerful Monolog The library provides a simple log abstraction layer. By default, Larave is configured to storage/logs
The directory generates log files for applications every day. You can use Log
Facade Log information to log:
<? php namespace App\Http\Controllers; use App\User; use Illuminate\Support\Facades\Log; use App\Http\Controllers\Controller; class UserController extends Controller { /** *Display the properties of the specified user * * @param int $id * @return Response */ public function showProfile($id) { Log::info('Showing user profile for user: '.$ id); return view('user.profile', ['user' => User::findOrFail($id)]); } }
The logger provides RFC 5424 Eight log levels defined in: emergency
、 alert
、 critical
、 error
、 warning
、 notice
、 info
and debug
。
Log::emergency($error); Log::alert($error); Log::critical($error); Log::error($error); Log::warning($error); Log::notice($error); Log::info($error); Log::debug($error);
Context Information
The context data will also be passed to the log method in the form of an array, and then formatted and displayed together with the log message:
Log::info('User failed to login.', ['id' => $user->id]);
Access the underlying Monolog instance
Monolog has multiple processors for logging. If necessary, you can access the underlying Monolog instance used by Larave:
$monolog = Log::getMonolog();