关于php:Laravel8学习笔记日志组件

8次阅读

共计 1317 个字符,预计需要花费 4 分钟才能阅读完成。

配置

配置文件 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%'
            ));
        }
    }
}
正文完
 0