3

Laravel8学习笔记-日志组件

 2 years ago
source link: https://segmentfault.com/a/1190000040848868
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Laravel8学习笔记-日志组件

配置文件 config/logging.php

默认情况下,Laravel 使用 stack 通道来记录日志信息,stack 通道被用于聚合多个日志通道到单个通道。

例:single通道默认写入larave.log文件,daily通道默认写入larave-*.log文件,若配置stack如下

'stack' => [
  'driver' => 'stack',
  'channels' => ['single','daily'],
]

则日志会同时写入larave.log和larave-*.log文件

LOG_LEVEL=debug 日志信息被通道记录所必须达到的最低「级别」

emergencyalertcriticalerrorwarningnoticeinfodebug

假设LOG_LEVEL=error,则Log::debug('An informational message.');不会记录日志

写入日志信息

Log::emergency($error);
Log::alert($error);
Log::critical($error);
Log::error($error);
Log::warning($error);
Log::notice($error);
Log::info($error);
Log::debug($error);

写入上下文信息

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

//local.INFO: User failed to login. {"id":123} 

写入指定通道

'test' => [
  'driver' => 'single',
  'path' => storage_path('logs/laravel.log'),
],

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

通道自定义

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

注:所有「tap」类都通过服务容器解析,所以他们需要的所有构造函数依赖都会被自动注入。

<?php

namespace App\Logging;

use Monolog\Formatter\LineFormatter;

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(new LineFormatter(
                '[%datetime%] %channel%.%level_name%: %message% %context% %extra%'
            ));
        }
    }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK