Laravel Basic Tutorial--Errors and logs

Source: Internet
Author: User
Tags bugsnag

Errors and Logs

Brief introduction

When you start a new Laravel project, you will definitely need to deal with errors and exceptions, and these laravel are already configured for you. In addition, the Laravel integrates the Monolog Log component library, which provides a variety of powerful log processors.

Configuration

Error details

The degree of error detail displayed in your app via the browser is configured through the debug option in your config/app.php profile. The default configuration item complies with the APP_DEBUG environment variable in the. env file.

Log mode

Larvel provides several out-of-the-box logging modes: Single,daily,syslog and errorlog. For example, if you want to use the daily date file logging to replace the default single-file logging method. You can simply set the value of the log option in the config/app.php configuration file:

' Log ' = ' daily '

When using daily log mode, Laravel will only retain log files for 5 days by default. If you need to keep more log files, you need to add the log_max_files option in the config/app.php file:

' Log_max_files ' = 30

Customizing the Monolog Configuration

If you want to have complete control over the Monolog configuration in your application, you can use the Configuremonologusing method of the app. You should make a call to the method in the bootstrap/app.php file, and you should put it before returning $app:

$app->configuremonologusing (function ($monolog) {  $monolog->pushhandler (...);}); return $app;

By default, Laravel records all levels of the log. In a production environment, you might want to log only certain levels of logs, which you can do by adding the log_level option to the app.php configuration file. Laravel logs this level and logs more advanced than this level log. For example, if you set Log_level to error, it will log messages for Error,critical,alert and emergency levels:

' Log_level ' = app_env (' App_log_level ', ' Debug '),

Exception handling

All exceptions will be handled in the App\exceptions\handler class. The class contains two methods: report and Render. We will make a detailed analysis of the two methods.

Report method

The report method is used to log exceptions or send exceptions to other services, such as Bugsnag or Sentry. By default, the report method simply passes the exception to the base class of the exception record. In fact, you are free to record anomalies according to your own wishes.

For example, if you want to record different types of exceptions in different ways, you can use the PHP instanceof method to do the filtering:

/** * Report or log an exception. * * This was a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \exception $e * @return void */Public fun Ction report (Exception $e) {   if ($e instanceof customexception) {     //   }   return Parent::report ($e);}

Ignore exceptions by type

The $dontReport property of the exception handling class contains an array of exception classes that need to be ignored. Exceptions of the type in this array will not be logged. The default 404 type of error is not recorded in the log file, and you can omit the exception class name in this array as needed.

Render method

The Render method is used to convert the exception to the response information passed back to the browser. The default exception is passed to the base class and a response is returned. In fact, you are free to customize the response as needed:

/** * Render An exception to an 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 ', [], and;  }  Return Parent::render ($request, $e);}

HTTP exception

Some exceptions are error codes that describe HTTP directly from the server. For example, this could be a "page not found" error (404), an "Unauthorized" error (401), or a "development error" (500). In order to quickly generate this type of response in your app, you can use the following method:

Abort (404);

The Abort method immediately raises an exception that is rendered in exception handling. You can also provide an optional response text in the method:

Abort (403, ' unauthorized action. ');

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

Custom HTTP Error page

Laravel makes it easy to create custom error pages based on HTTP response status codes. For example, you might want to customize an error page to provide a 404 HTTP status code. You can create a resoucres/views/errors/404.blade.php file. The file automatically provides the service when the app throws a 404 error.

The name of the view under this directory should correspond to the HTTP status code.

Log

Laravel's log system is based on the powerful Monolog class library. By default, Laravel sets the Storage/logs directory to hold the log files. You can use the log mask to record logging information:

 
  User:findorfail ($id)]);}   }

The logger defines 8 log levels according to the RFC 5424 specification: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

You can pass an array of context data into the log method, and the context data will be formatted and displayed in the log message:

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

Accessing the underlying Monolog instance

Monolog has several additional log processing methods. If you want, you can access the underlying Monolog instance in Laravel using the following method:

$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.