Laravel 5.3 learning notes errors & logs, laravel5.3

Source: Internet
Author: User

Laravel 5.3 learning notes errors & logs, laravel5.3

1. Introduction

Laravel has configured error and Exception Handling for us by default. we trigger an exception in the App \ Exceptions \ Handler class and return the response to the user. In this tutorial, we will explore this class in depth.

Laravel also integrates the Monolog logstore to provide a variety of powerful log processors. By default, Laravel has configured some processors for us. We can select a single log file, you can also choose to record the error information to the system log.

2. Configuration

Error details display

The debug configuration item in config/app. php controls the number of error details displayed by the browser. By default, this configuration item is set through the Environment Variable APP_DEBUG in the. env file.

For local development, you should set the environment variable APP_DEBUG to true. In the production environment, this value should be set to false. If it is set to true in the production environment, some sensitive configuration values may be exposed to end users.

Log storage

By default, Laravel supports the log Methods single, daily, syslog, and errorlog. If you want to generate a log file by day instead of generating a single file, set the log value in config/app. php as follows:

'log' => 'daily'

Maximum lifecycle of log files

When the daily log mode is used, Laravel retains the logs of the last five days by default. to modify this time, you need to add log_max_files to the app configuration file:

'log_max_files' => 30

Log error level

When using Monolog, log messages may have different error levels. By default, Laravel writes all logs to the storage directory. However, you may want to configure the lowest error level in the production environment, this can be done through the configuration file app. php is implemented by adding the configuration item log_level.

After this configuration item is configured, Laravel records all logs with an error level greater than or equal to this specified level. For example, the default log_level is error, logs at the error, critical, alert, and emergency levels will be recorded:

'log_level' => env('APP_LOG_LEVEL', 'error'),

Note: Monolog supports the following error levels: debug, info, notice, warning, error, critical, alert, and emergency.
Custom Monolog Configuration

If you want to fully control the Monolog configuration in the application, you can use the configureMonologUsing method. You need to call this method before the bootstrap/app. php file returns the $ app variable:

$app->configureMonologUsing(function($monolog) {  $monolog->pushHandler(...);});return $app;

3. Exception Processor

All Exceptions are handled by class App \ Exceptions \ Handler. This class contains two methods: report and render. The two methods are described in detail below.

Report Method

The report method is used to record exceptions and send them to external services such as bugsng or Sentry. By default, the report method only transmits exceptions to the basic classes recorded by exceptions, of course, you can also record and handle exceptions as needed.

For example, if you need to report different types of exceptions in different ways, you can use the instanceof comparison operator in PHP:

/*** Report or record exceptions ** This is a great spot to send exceptions tions to Sentry, bugsng, etc. ** @ param \ Exception $ e * @ return void */public function report (Exception $ e) {if ($ e instanceof CustomException) {//} return parent :: report ($ e );}

An error occurred while ignoring the data type.

The $ dontReport attribute of the exception processor contains an array of non-recorded exception types. By default, 404 error exceptions are not written to log files, if needed, you can add other exception types to this array:

/** * A list of the 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

The render method converts a given exception to an HTTP Response sent to the browser. By default, an 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 as needed:

/*** Render the Exception to the HTTP Response ** @ 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 exceptions

Some exceptions describe the HTTP Error code from the server. For example, this may be a "Page not found" error (404) or "authentication failure error" (401) or the 500 error caused by a program error. to generate such a response in the application, you can use the abort method:

Abort (404 );

The abort method immediately raises an exception that will be rendered by the exception processor. In addition, you can provide the response description as follows:

Abort (403, 'unauthorized action .');

This method can be used at any time point in the request lifecycle.

Custom HTTP Error Page

In Laravel, it is very easy to return error pages with different HTTP status codes. For example, if you want to customize the 404 error page, create a resource/views/errors/404. blade. PHP file, which is used to render all 404 errors returned by the program. Note that the view name in this directory should match the corresponding HTTP status code.

5. Logs

Laravel provides a simple log abstraction layer based on the powerful Monolog library. By default, Laravel is configured to generate log files for applications every day under the storage/logs directory, you can use the Log facade to record the Log information to the Log:

<? Phpnamespace App \ Http \ Controllers; use Log; use App \ User; use App \ Http \ Controllers \ Controller; class UserController extends Controller {/*** display the attributes 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 eight log levels defined in RFC 5424: 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 is also transmitted to the log method in an array format and displayed together with the log message:

Log::info('User failed to login.', ['id' => $user->id]);

Access the underlying Monolog instance

Monolog has multiple log processors. If needed, you can access the underlying Monolog instance used by Laravel:

$monolog = Log::getMonolog();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.