log


Build log stack

  • Write log message
  • Write to the specified channel
    • Advanced Monolog log channel customization
  • Customized Monolog channel
  • Create channel through factory
    • Introduction

      To help you understand more about what is happening in your application, Laravel provides a powerful logging service that allows you to record log messages, system error logs to files, and even use Slack notifications to your entire team.

      In the Laravel framework, Laravel uses the Monolog library, which provides support for a variety of powerful log processing. Laravel makes it easy to configure these handlers, allowing you to mix and match them for custom application log processing.

      Configuration

      All application logging system configuration is located at config/logging.php in the configuration file. This file allows you to configure your application log channels, so be sure to review each available channel and their options. Of course, we'll review some of the commonly used options below.

      By default, Laravel will use stack to log messages. The stack channel is used to aggregate multiple log channels into a single channel. For more information about the stack, view the following documentation.

      Configure channel name

      By default, Monolog is instantiated using a "channel name" that matches the current environment, such as production orlocal. To change this value, add a name option to your channel configuration:

      'stack' => [  
        'driver' => 'stack',    
        'name' => 'channel-name',    
        'channels' => ['single', 'slack'],
       ],

      Available channel drivers

      A Monolog-driven A Monolog that can use any Monolog handler Factory driverA driver that calls the specified factory to create a channel

      {tip} For monolog and custom drivers, see Advanced Channel Customization

      Configuring Single and Daily channels

      single and daily channels contain three optional configuration items: bubble, permission and locking.

      NameDescription
      stackA wrapper that facilitates the creation of "multi-channel" channels
      singleSingle file or Log channel-based path (StreamHandler)
      dailyA daily rotating Monolog-driven one RotatingFileHandler
      slackA Monolog-driven SlackWebhookHandler
      syslogA Monolog-driven SyslogHandler
      ##errorlog ErrorLogHandler
      monolog
      custom
      NameDescriptionDefault value
      bubbleAfter the message is processed, indicate whether the message is pushed to other channelstrue
      permissionLog file permission644
      lockingAttempt to lock the log file before writingfalse

      Configuring a Slack channel

      slack The channel requires the url configuration option. This URL should match an incoming webhook you configured for your Slack team.

      ##Building a log stack

      As mentioned earlier, the

      stack driver allows you to log in a single Integrate multiple channels into a channel. Let's look at how to use the log stack through a production-level application configuration example: :

      'channels' => [ 
         'stack' => [     
            'driver' => 'stack',        
            'channels' => ['syslog', 'slack'],   
           ],    
            'syslog' => [      
             'driver' => 'syslog',        
             'level' => 'debug',    
            ],    
            'slack' => [       
                'driver' => 'slack',        
                'url' => env('LOG_SLACK_WEBHOOK_URL'),        
                'username' => 'Laravel Log',        
                'emoji' => ':boom:',        
                'level' => 'critical',    
               ],
         ],

      Let's analyze this configuration. The first thing to note is that

      stack aggregates two other channels with the help of its channels option: syslog and slack . Therefore, when logging a log message, both channels have the opportunity to complete the log message recording:

      Log level

      Please pay attention to the

      syslog# in the above example. level configuration items that exist in ## and slack. This option determines the minimum "level" of logging that needs to be logged by this channel. Monolog (a powerful Laravel logging service) accepts all levels defined in the RFC 5424 specification: emergency, alert, critical, error, warning, notice, info and debug. Assume we use the

      debug

      method to record log messages:

      Log::debug('An informational message.');
      According to our configuration, the

      syslog

      channel will record the message to the system log; But because the error message is not critical or higher, it will not be sent to Slack. If we log an emergency message, it will be sent to syslog and Slack because the level of emergency is higher than the lowest level limit for both channels:

      Log::emergency('The system is down!');

      Write log message

      You can use the

      Log

      facade to write information to the log. As mentioned before, logging provides the available logging levels defined in the RFC 5424 specification: emergency, alert, critical, error, warning, notice, info and debug:

      Log::emergency($message);
      Log::alert($message);
      Log::critical($message);
      Log::error($message);
      Log::warning($message);
      Log::notice($message);
      Log::info($message);
      Log::debug($message);
      Therefore, you can call any of these methods The method records the corresponding level of logs. By default, messages are written to the default logging channel defined in the

      config/logging.php

      configuration file:

      <?php
         namespace App\Http\Controllers;use App\User;
         use Illuminate\Support\Facades\Log;
         use App\Http\Controllers\Controller;
         class UserController extends Controller{   
          /**
           * 显示给定用户的配置信息。
           *
           * @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)]);   
             }
          }

      Context information

      You can pass an array of context data to the log method. The information will be formatted and displayed with the log message:

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

      Write to the specified channel

      Sometimes you may want to write messages to a channel other than the application's default channel. You can use the channel method of the Log facade to obtain any channel defined in the configuration file and write the message into it:

      Log::channel('slack')->info('Something happened!');

      If you want to create a channel consisting of multiple The on-demand recording stack composed of channels can use the stack method:

      Log::stack(['single', 'slack'])->info('Something happened!');

      ##Highly customized Monolog channel

      Customizing Monolog for channels

      Sometimes you need to fully control the Monolog of an existing channel: For example, you may want to To configure a custom Monolog

      FormatterInterface implementation for log processing of a given channel:

      First define a

      tap array in the channel configuration. The tap array contains a list of classes that have the opportunity to be used to customize the Monolog instance after the channel is created:

      'single' => [   
       'driver' => 'single',    
       'tap' => [App\Logging\CustomizeFormatter::class],    
       'path' => storage_path('logs/laravel.log'),    
       'level' => 'debug',
      ],

      Once the

      tap option is configured in the channel, To prepare a class for a custom Monolog instance. This class requires a method: __invoke, which accepts an Illuminate\Log\Logger instance as its parameter. Illuminate\Log\Logger The instance proxies all method calls to the underlying Monolog instance:

      <?php
         namespace App\Logging;
         class CustomizeFormatter{   
          /**
           * 自定义给定的日志实例。
           *
           * @param  \Illuminate\Log\Logger  $logger
           * @return void
           */   
         public function __invoke($logger)   
          {      
            foreach ($logger->getHandlers() as $handler) {        
                $handler->setFormatter(...);      
               }  
            }
         }

      {tip} All "tap" classes are resolved by the service container, Therefore any constructors that depend on them will be automatically injected.

      Create a Monolog processor channel

      Monolog has a variety of available processors. In some cases, you will want to create only a Monolog-driven log type with a specific processor. These channels can be created using the

      monolog driver.

      When using the

      monolog driver, the handler configuration item is used to specify the instantiated processor. If the processor's constructor requires parameters, you can use the optional with configuration item to specify:

      'logentries' => [   
       'driver'  => 'monolog',    
       'handler' => Monolog\Handler\SyslogUdpHandler::class,    
       'with' => [      
         'host' => 'my.logentries.internal.datahubhost.company.com',        
         'port' => '10000',   
         ],
        ],

      Monolog formatting

      Use

      monolog When driven, Monolog's LineFormatter is used as the default formatter. Of course, you can also use the formatter and formatter_with configuration items to customize the formatting processor type:

      'browser' => [  
        'driver' => 'monolog',    
        'handler' => Monolog\Handler\BrowserConsoleHandler::class,    
        'formatter' => Monolog\Formatter\HtmlFormatter::class,    
        'formatter_with' => [      
          'dateFormat' => 'Y-m-d',  
          ],
        ],

      If the Monolog processor used can provide its own format generation processor, you can specify the

      formatter configuration item as default:

      'newrelic' => [ 
         'driver' => 'monolog',    
         'handler' => Monolog\Handler\NewRelicHandler::class,    
         'formatter' => 'default',
      ],

      Creating channels through factories

      If you want to define a completely custom channel, you have full control over Monolog instantiation and configuration, you can configure it in config/logging.php Specify the custom driver type in the file. Your configuration should include a via option pointing to the factory class that will be called to create the Monolog instance:

      'channels' => [  
        'custom' => [      
          'driver' => 'custom',        
          'via' => App\Logging\CreateCustomLogger::class,   
          ],
       ],

      Once the custom channel is configured, you can define the creation Class for Monolog instances. This class only needs one method: __invoke, which can return a Monolog instance:

      <?php
        namespace App\Logging;use Monolog\Logger;
        class CreateCustomLogger{    
            /**
           * 创建一个 Monolog 实例.
           *
           * @param  array  $config
           * @return \Monolog\Logger
           */   
          public function __invoke(array $config) 
            {     
               return new Logger(...);  
             }
           }
      This article was first published on the LearnKu.com website.