Basic components - logs

Brief introduction

   To help you learn more about what happened applications, Laravel provides a powerful service to log information to a log file, system error log, even Slack in order to inform the entire team.

   Under log engine, Laravel integrated Monolog logging library in order to provide a variety of powerful logging processor, allowing you to customize your own log processing applications through them.

Configuration

   All system configuration application logs are stored in the configuration file  config/logging.php , the file allows you to configure the application log channel, so be sure to check each of the available channels and their configuration items. Here we take a look at some of the configuration items.

   By default, Laravel use  stack channel to log information stack channel is used for aggregating a plurality of channels into a single channel logs, on building more  stack information, please read.

   Configure the channel name

   By default, Monolog by the current "channel name" environment matching instantiation, for example  production , or  local, to change this value, add  name items to channel configuration:

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

Effective channel drivers list

name description
stack Used to create a "multi-channel" channel aggregator
single Based on single-file / path channel log ( StreamHandler)
daily Based  RotatingFileHandler Monolog driven in days for the log partition dimensions
slack Based  SlackWebhookHandler Monolog drive
syslog Based  SyslogHandler Monolog drive
errorlog Based  ErrorLogHandler Monolog drive
monolog Monolog into the drive, you can use all supported processors Monolog
custom Call the specified drive to create a channel change

Note: View advanced custom document learning channel  monolog and  custom drive.

   Single channel configuration and Daily

   single And the  daily channel has three optional configuration bubbleitem: , permission , and  locking.

name description Defaults
bubble Indicates whether the message after being processed to the other channels bubbling true
permission Log file permissions 644
locking Before the log file is written to try to lock it false

   Slack channel configuration

   slack Channel needs a  url configuration item, the URL and you need to configure Slack team requested URL matches.

   Build log stack

     As mentioned above, stack the drive allows you to log multiple channels into a single channel, in order to explain how, let's look at an example you might see in a production environment configuration:

'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 dissect this configuration. First, note that  stack passage through  channels entry channels two other polymerization: syslog and  slack. Therefore, when the log information, which has the opportunity to record two channels of information.

   Log Level

     Note that the above example  syslog and  slack channel configuration appears in  level configuration item, the configuration item determines the log information is necessary to achieve the lowest channel recording 'level. " Monolog, defined as Laravel provide support services all log log level (from low to high) in RFC 5424 specification: Emergency (emergency, emergencies), alert (pop-up warning), critical (dangerous), error ( error), warning (warning), notice (notice, note), info (information) and debug (debug) .

     Therefore, if we use the  debug method to record log information:

Log::debug('An informational message.');

     Given our configuration, syslog channel information will be recorded in the system log; however, due to an error message is not  critical level or higher, it will not be sent to Slack. But if we are recording the  emergency level of information, it will be sent to the system log and Slack, because the  emergency level is higher than the minimum threshold level of two channels:

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

Write log information

   You can use the  Log facade logging information, as described above, provides a definition of eight kinds of log system log level in 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::debug($error);

   Thus, you can call any of a method wherein the level corresponding to record log information, by default, the information is written to the configuration file by  config/logging.php default channel configured:

<?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)]);
    }
}

   Contextual information

     Context data is also transmitted to the log in an array method, and then the log information is formatted and displayed together:

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

   Write to the specified channel

     Sometimes you may want to log information to a channel rather than the default channel applications. To achieve this purpose, you can use  Log on the facade of the  channel method to obtain the configuration file defines the channel and written into the log:

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

     If you want to create an on-demand log stack composed of a plurality of channels, you can use  stack the method:

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

Senior Monolog custom channel

   Custom channel is Monolog

     Sometimes you may need full control Monolog configuration in a particular channel, for example, you might want to give the processor a given channel configuration Monolog is a custom  FormatterInterface implementation.

     As a start, we define a channel in the configuration of the  tap array, the  tap array contains the list of classes may need Monolog instance custom created:

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

     Configured on the channel  tap after the item, you can define a custom class instance of Monolog. This class is only required to obtain a  Illuminate\Log\Logger instance method: __invoke, Illuminate\Log\Logger examples will delegate all method calls the underlying Monolog instance:

<?php

namespace App\Logging;

class CustomizeFormatter
{
    /**
     * Customize the given logger instance.
     *
     * @param  \Illuminate\Log\Logger  $logger
     * @return void
     */
    public function __invoke($logger)
    {
        foreach ($logger->getHandlers() as $handler) {
            $handler->setFormatter(...);
        }
    }
}

Note: All "tap" classes are resolved through the service container, so all they need to rely on the constructor will be automatically injected.

Create a channel processor Monolog

   Monolog multiple processors are available, and in some cases, you want to create a log record of the type specified only with the drive processor Monolog instance, these channels can  monolog create drive.

Using  monolog the drive, handler the configuration item is used to specify which of the processor instance, as an optional constructor parameter processor can use  handler_with the configuration item to set:

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

   Monolog formatting tools

     Use  monolog when driving, Monolog  LineFormatter will be used as the default formatting tools. However, you can also use  formatter and  formatter_with type of configuration items to customize incoming processor formatting tools:

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

     If you are using a formatting tool capable of providing their own Monolog processor can be  formatter configured to set the value of the item  default:

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

Create a channel through the factory

   If you want to define a complete custom channel so Monolog full control over instantiation and configuration, the configuration file can be  config/logging.php specified in a  custom drive type. In addition, you should include a configuration  via item to specify a factory class is called to create Monolog instance:

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

   Configure  custom the channel, you can create a class defined Monolog instance, this class requires only a method to return Monolog instance: __invoke:

<?php

namespace App\Logging;

use Monolog\Logger;

class CreateCustomLogger
{
    /**
     * Create a custom Monolog instance.
     *
     * @param  array  $config
     * @return \Monolog\Logger
     */
    public function __invoke(array $config)
    {
        return new Logger(...);
    }
}

 

Guess you like

Origin www.cnblogs.com/mzhaox/p/11272001.html