Exception handling&error log


 LARAVEL-errorhanding

brief 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.
Note: For the underlying principle and implementation of Laravel exception handling, refer to the college's tutorial for more information—— "In depth discussion of PHP error exception handling mechanism and corresponding implementation of the underlying Laravel framework"
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.

to configure

Error Details

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 log file types of 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'
Other log types are as follows:
  • single : So the log information will be recorded in a single log file
  • syslog : By system syslog Service processing log information
  • errorlog : via PHP error_log Processor processing log information
Note: The underlying processing mechanism can refer to Illuminate\Log\LogServiceProvider Implementation logic in.
Maximum life cycle of log file

use daily In the log mode, by default, Larave will keep the latest five Day log. 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, Larave writes all levels of logs to the storage. However, in the production environment, you may want to configure the minimum error level by using the app.php Add configuration item in log_level To achieve.

After the configuration item is configured, Larvel will record all logs with an error level 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;

Custom Channel Name

By default, Monolog will be instantiated by a name that matches the current environment, such as production or local To modify this value, you need to add log_channel Configuration item to configuration file app.php

 'log_channel' => env('APP_LOG_CHANNEL', 'my-app-name'),

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); }

report auxiliary function

Sometimes you may need to report an exception and continue processing the current request. auxiliary function report Allows you to use the exception handler's report Method to quickly report an exception without rendering the error page:

 public function isValid($value) { try { // Validate the value... } catch (Exception $e) { report($e); return false; } }

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);

}

Reportable&Renderable Exception

Except in the exception handler's report and render In addition to the exception type check in the method, you can also directly define the report and render method. When these methods exist in the exception, the framework will automatically call them:
 <? php namespace App\Exceptions; use Exception; class RenderException extends Exception { /** * Report the exception. * * @return void */ public function report() { // } /** * Render the exception into an HTTP response. * * @param  \Illuminate\Http\Request * @return \Illuminate\Http\Response */ public function render($request) { return response(...); } }

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 operation');
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:
 {{ $exception->getMessage() }}

journal

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 Record the log information to the 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();

give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: Request form validation and error handling

>>Next: Localization of view rendering: enable your application to easily support multiple languages