Laravel 5.3 Error & Log _php tips for learning Notes

Source: Internet
Author: User
Tags auth exception handling bugsnag

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. We'll delve into this class in depth in this tutorial.

In addition, Laravel also integrates the Monolog log Library to provide a variety of powerful log processors, by default Laravel has configured some processors for us, we can select individual log files, or we can choose to log error messages to the system logs.

2, configuration

Error details display

The Debug configuration entry in profile 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 value to True. In a production environment, this value should be set to false. If the production environment is set to true, it is possible to expose some sensitive configuration values to end users.

Journal Storage

By default, Laravel supports log methods single, daily, Syslog, and errorlog. If you want the log file to be generated on a daily basis instead of generating a single file, you should set the log value in the configuration file config/app.php as follows:

'log' => 'daily'

Maximum log file life cycle

When using the daily log mode, laravel defaults to keep the last 5 days of the log, if you want to modify this time, you need to add a configuration Log_max_files to the app configuration file:

'log_max_files' => 30

Log Error level

When using Monolog, the log message may have different error levels, by default, Laravel writes all the logs to the storage directory, but in a production environment you may want to configure the lowest error level, which can be done by adding a configuration entry in the profile app.php Log_ level to achieve.

When the configuration item is configured, Laravel records all logs that have an error level greater than or equal to this specified level, for example, the default log_level is error, the error, critical, alert, and emergency-level log information will be logged:

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

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

If you want to fully control the Monolog configuration in your 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 the class App\exceptions\handler, which contains two methods: the Render and the. We'll elaborate on these two methods below.

The method of the

The method is used to record an exception and send it to an external service such as Bugsnag or Sentry, by default, the method only passes the exception to the base class where the exception is recorded, and you can, of course, record the exception and handle it as you want.

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

/**
 * Report or Record exception
 *
 * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
 * *
 @param \exception $e
 * @return void
 *
/Public Function Exception $e) {
  if ($e instanceof Cu stomexception) {
    //
  } return

  Parent::report ($e);


Ignore exceptions by type

The exception handler's $dontreport property contains an array of exception types that will not be logged, by default, 404 error exceptions are not written to the log file, and you can add other exception types to this array if needed:

/**
 * A List of the exception types that should is not 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 is responsible for translating the given exception into an HTTP response sent to the browser, by default, the exception is passed to the base class that generated the response for you. Of course, you can also check the exception type or return a custom response according to your own needs:

/**
 * Renders an 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 ', [];
  }

  Return Parent::render ($request, $e);
}

4, HTTP exception

Some exceptions describe HTTP error codes from the server, for example, this could be a "page not found" error (404), "Authentication Failure Error" (401) or a 500 error caused by a program error, and the Abort method can be used to generate such a response in an application:

Abort (404);

The Abort method immediately throws an exception that is rendered by the exception handler, and you can also provide a response description like this:

Abort (403, ' unauthorized action. ');

This method can be used at any point in the life cycle of the request.

customizing HTTP Error pages

In Laravel, the error page that returns different HTTP status codes is simple, for example, if you want to customize the 404 error page, create a resources/views/errors/404. The blade.php file, which is used to render all 404 errors returned by the program. Note that the name of the view under this directory should match the corresponding HTTP status code.

5, log

Laravel provides a simple log abstraction layer based on a powerful Monolog library, by default, Laravel is configured to generate log files for applications every day under the Storage/logs directory, and you can log information to logs using log façade:

<?php

namespace App\http\controllers;

Use Log;
Use App\user;
Use App\http\controllers\controller;

Class Usercontroller extends controller{
  /**
   * Displays the properties of the specified user
   * *
   @param int $id
   * @return Response
   */Public
  function Showprofile ($id)
  {
    log::info (' Showing user profiles 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::d ebug ($error);

Contextual information

Contextual data is also passed to the log method as an array, and is formatted and displayed along with the log message:

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

Accessing the underlying Monolog instance

Monolog has multiple processors available for logging, and if necessary, 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: info-contact@alibabacloud.com 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.