Home > php教程 > PHP开发 > body text

Laravel 5.3 Study Notes Errors & Logs

高洛峰
Release: 2016-12-22 15:56:45
Original
1091 people have browsed it

1. Introduction

Laravel has configured error and exception handling for us by default. We trigger exceptions in the AppExceptionsHandler class and return the response to the user. In this tutorial we will explore this class in depth.

In addition, Laravel has also integrated the Monolog logging library to provide a variety of powerful log processors. By default, Laravel has configured some processors for us. We can choose a single log file or log error information to System log.

2. Configure

Error details display

The debug configuration item in the configuration file 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 a production environment, this value should be set to false. If set to true in a production environment, it is possible to expose some sensitive configuration values ​​to end users.

Log storage

By default, Laravel supports the log methods single, daily, syslog and errorlog. If you want log files 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 daily log mode, Laravel retains the last 5 days of logs for us by default. 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 levels

When using Monolog, log messages may have different error levels. By default, Laravel writes all logs to the storage directory, but in a production environment, you may want to configure the minimum error level. This can be done via This is achieved by adding the configuration item log_level in the configuration file app.php.

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

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

Note: Monolog supports the following error levels - debug, info, notice, warning, error, critical, alert, emergency.
Customized 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;
Copy after login

3. Exception handler

All exceptions are handled by the class AppExceptionsHandler, which contains two methods: report and render. Below we elaborate on these two methods.

report method

The report method is used to record exceptions and send them to external services such as Bugsnag or Sentry. By default, the report method just passes the exception to the base class where the exception is logged. Of course, you can also press it according to your own needs. Record exceptions and handle them accordingly.

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

/**
 * 报告或记录异常
 *
 * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
 *
 * @param \Exception $e
 * @return void
 */
public function report(Exception $e){
  if ($e instanceof CustomException) {
    //
  }
 
  return parent::report($e);
}
Copy after login

Ignore exceptions by type

The $dontReport attribute of the exception handler contains an Array of recorded exception types. By default, 404 error exceptions will not be written to the log file. If necessary, 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,
];
Copy after login

render method

render method is responsible for giving Defined exceptions are converted into HTTP responses sent to the browser. By default, exceptions are 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 own needs:

/**
 * 将异常渲染到HTTP响应中
 *
 * @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);
}
Copy after login

4. HTTP exception

Some exceptions describe HTTP error codes from the server. For example, this may be a "page Not found" error (404), "Authentication failed error" (401) or a 500 error caused by a program error. In order to generate such a response in the application, you can use the abort method:

abort(404);

The abort method will immediately raise 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 in the request life cycle Use at any time.

Custom HTTP Error Page

In Laravel, returning error pages with different HTTP status codes is simple. For example, if you want to customize a 404 error page, create a resources/views/errors/404.blade.php file. , this view file is used to render all 404 errors returned by the program. It should be noted that the view naming in this directory should match the corresponding HTTP status code.

5. Log

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

<?php
 
namespace App\Http\Controllers;
 
use Log;
use App\User;
use App\Http\Controllers\Controller;
 
class UserController extends Controller{
  /**
   * 显示指定用户的属性
   *
   * @param int $id
   * @return Response
   */
  public function showProfile($id)
  {
    Log::info(&#39;Showing user profile for user: &#39;.$id);
    return view(&#39;user.profile&#39;, [&#39;user&#39; => User::findOrFail($id)]);
  }
}
Copy after login

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

Context data will also be passed to the log method in the form of an array, It is then formatted and displayed along with the log message:

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

Access to the underlying Monolog instance

Monolog has multiple processors that can be used for logging. If necessary, you can access the underlying Monolog instance used by Laravel:

$monolog = Log::getMonolog();

More Laravel 5.3 Study Notes Errors & Logs For related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!