Hyperf后台日志开关设置

设置记录运行日志的步骤主要有几个地方,这里需要注意的是config.php设置的日志是终端显示的设置。

我们这里是把终端的运行日志保存到log文件里面

这里在文档里面也有介绍到:https://hyperf.wiki/2.0/#/zh-cn/logger?id=stdout-日志

这里简单介绍下,就是在app目录下添加Log.php和StdoutLoggerFactory.php两个文件

然后在dependencies.php申明依赖

配置日志的路径和等级在logger.php

 [
        'handler' => [
            'class' => Monolog\Handler\StreamHandler::class,
            'constructor' => [
                // 设置日志路径
                'stream' => BASE_PATH . '/runtime/logs/hyperf.log',
                // 设置日志等级
                'level' => Monolog\Logger::INFO,
            ],
        ],
        'formatter' => [
            'class' => Monolog\Formatter\LineFormatter::class,
            'constructor' => [
                'format' => null,
                'dateFormat' => null,
                'allowInlineLineBreaks' => true,
            ],
        ],
    ],
    'sql' => [
        'handler' => [
            'class' => Monolog\Handler\StreamHandler::class,
            'constructor' => [
                'stream' => BASE_PATH . '/runtime/logs/hyperf_sql.log',
                'level' => Monolog\Logger::INFO,
            ],
        ],
        'formatter' => [
            'class' => Monolog\Formatter\LineFormatter::class,
            'constructor' => [
                'format' => null,
                'dateFormat' => null,
                'allowInlineLineBreaks' => true,
            ],
        ],
    ],    
];

如果需要对sql语句另外设置日志文件的话需要在Listener中DbQueryExecutedListener.php修改相应配置

这里贴上我设置的代码

logger = $container->get(LoggerFactory::class)->get('sql','sql');
    }

    public function listen(): array
    {
        return [
            QueryExecuted::class,
        ];
    }

    /**
     * @param QueryExecuted $event
     */
    public function process(object $event)
    {
        if ($event instanceof QueryExecuted) {
            $sql = $event->sql;
            if (! Arr::isAssoc($event->bindings)) {
                foreach ($event->bindings as $key => $value) {
                    $sql = Str::replaceFirst('?', "'{$value}'", $sql);
                }
            }
            // 记录SQL日志
            $this->logger->info(sprintf('[%s] %s', $event->time, $sql));
        }
    }
}

 

你可能感兴趣的:(php,经验分享,后端)