3.6 日志
hyperf/logger
组件是基于 psr/logger 实现的,默认使用 monolog/monolog 作为驱动,在 hyperf-skeleton
项目内默认提供了一些日志配置,默认使用 MonologHandlerStreamHandler
, 由于 Swoole
已经对 fopen
, fwrite
等函数进行了协程化处理,所以只要不将 useLocking
参数设置为 true
,就是协程安全的。
安装composer包
代码语言:javascript复制composer require hyperf/logger
Bash
Copy
- 配置文件:
config/autoload/logger.php
可以配置日志位置,格式例如年月日,以及日志等级
<?php
return [
'default' => [
'handler' => [
'class' => MonologHandlerStreamHandler::class,
'constructor' => [
'stream' => BASE_PATH . '/runtime/logs/hyperf.log',
'level' => MonologLogger::DEBUG,
],
],
'formatter' => [
'class' => MonologFormatterLineFormatter::class,
'constructor' => [
'format' => null,
'dateFormat' => null,
'allowInlineLineBreaks' => true,
]
],
],
];
PHP
Copy
使用:在构造函数中实例对象
代码语言:javascript复制<?php
namespace AppController;
use AppExceptionResourceException;
use HyperfHttpServerAnnotationAutoController;
use HyperfHttpServerAnnotationMiddleware;
use HyperfHttpServerAnnotationMiddlewares;
class IndexController extends AbstractController
{
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
public function __construct(HyperfLoggerLoggerFactory $loggerFactory)
{
$this->logger = $loggerFactory->get('log', 'default');
}
public function index()
{
$this->logger->info('hello world');
}
}
PHP
Copy
使用:封装Log类
代码语言:javascript复制<?php
namespace AppController;
use AppExceptionResourceException;
use HyperfHttpServerAnnotationAutoController;
use HyperfHttpServerAnnotationMiddleware;
use HyperfHttpServerAnnotationMiddlewares;
class IndexController extends AbstractController
{
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
public function index()
{
$this->logger = HyperfUtilsApplicationContext::getContainer()
->get(HyperfLoggerLoggerFactory::class)
->get('log', 'default');
$this->logger->info('hello world');
}
}
PHP
Copy