monolog 控制台日志

baitqt

首先 “config/log.php” 配置如下

return [
    'default' => [
        'handlers' => [
            [
                'class' => Monolog\Handler\RotatingFileHandler::class,
                'constructor' => [
                    runtime_path() . '/logs/webman.log',
                    7, //$maxFiles
                    Monolog\Logger::DEBUG,
                ],
                'formatter' => [
                    'class' => Monolog\Formatter\LineFormatter::class,
                    'constructor' => [null, 'Y-m-d H:i:s', true],
                ],
            ],
            [
                'class' => Monolog\Handler\StreamHandler::class,
                'constructor' => [
                    'php://stdout',
                     Monolog\Logger::DEBUG,
                ],
                'formatter' => [
                    'class' => Monolog\Formatter\LineFormatter::class,
                    'constructor' => [null, 'Y-m-d H:i:s.u', true],
                ],
            ]
        ],
    ],
];

将 vendor\monolog\monolog\src\Monolog\Handler\StreamHandler.php 中 streamWrite 函数改造如下

protected function streamWrite($stream, array $record): void
    {
        $content =  (string) $record['formatted'];
        if($this->getUrl() ==='php://stdout'){
            switch($record['level']){
                case Logger::DEBUG:
                    $content = "\33[1;34;40m".$content."\33[0m";
                    break;
                case Logger::INFO:
                    $content = "\33[1;32;40m".$content."\33[0m";
                    break;
                case Logger::NOTICE:
                    $content = "\33[1;39;40m".$content."\33[0m";
                    break;
                case Logger::WARNING:
                    $content = "\33[1;33;40m".$content."\33[0m";
                    break;
                case Logger::ERROR:
                case Logger::CRITICAL:
                    $content = "\33[1;31;40m".$content."\33[0m";
                    break;
                case Logger::ALERT:
                    $content = "\33[1;36;40m".$content."\33[0m";
                    break;
                case Logger::EMERGENCY:
                    $content = "\33[5;31;40m".$content."\33[0m";
                    break;
            }
        }
        fwrite($stream,$content);
    }

尝试打印输出

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

查看控制台效果
截图

1101 2 6
2个评论

Administration

6

  • 暂无评论
平头有杀气

改了,真好看啊,谢谢大佬~

  • 暂无评论

baitqt

200
积分
0
获赞数
0
粉丝数
2023-08-21 加入
×
🔝