关于php: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%'
            ));
        }
    }
}

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据