企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 日志 日志组件通常使用在开发环境中用来 debug,生产环境中监控程序异常与运行状态,基于 [PSR-3](https://www.php-fig.org/psr/psr-3/) 标准实现。 ## 组件 使用 [composer]([https://www.phpcomposer.com/](https://www.phpcomposer.com/)) 安装: ~~~ composer require mix/log ~~~ ## 依赖注入配置 - [beans/log.php](https://github.com/mix-php/mix-skeleton/tree/v2.1/manifest/beans/log.php) `rotate` 全部常量明细: - Mix\Log\FileHandler::ROTATE_HOUR - Mix\Log\FileHandler::ROTATE_DAY - Mix\Log\FileHandler::ROTATE_WEEKLY ## 获取实例 通过依赖配置获取实例: ~~~ /** @var \Mix\Log\Logger $log */ $log = context()->get('log'); ~~~ ## PSR 定义方法 | 方法 | | --- | | emergency($message, array $context = []) : bool | | alert($message, array $context = []) : bool | | critical($message, array $context = []) : bool | | error($message, array $context = []) : bool | | warning($message, array $context = []) : bool | | notice($message, array $context = []) : bool | | debug($message, array $context = []) : bool | | log($level, $message, array $context = []) : bool | - Sample: ``` $message = 'UserId: {userId}, Name: {name}'; $context = ['userId' => 1008, 'name' => 'your name']; $log->info($message, $context); // 将生成 20200304[_自增编号].log 文件 ``` ## 日志文件 [\Mix\Log\FileHandler::class](https://github.com/mix-php/mix-skeleton/tree/v2.1/manifest/beans/log.php#L41) 负责将日志写入到文件: - 日志目录:保存在 `dir` 属性定义的位置,需绝对路径。 - 日志文件格式:`文件前缀_轮转时间[_自增编号].log` ## 日志记录级别 配置中的 `levels` 字段设定了写入日志的级别,没有定义在里面的日志类型,不管是被动调用还是主动掉用,都不会写入到日志文件。 >[info] 日志记录级别对用户定义的新类型无效,比如上面 log 方法的 test 类型。 - 只记录 'error', 'info', 'debug' 日志,忽略其他类型的日志: ~~~ 'level' => ['error', 'info', 'debug'], ~~~ ## 自定义日志处理 Mix\Log\MultiHandler::class 可以传入任意多个日志处理器,其中 Mix\Log\StdoutHandler::class 是必须传入的,否则错误会没有终端输出,看不到程序的异常。 当用户想自己处理日志时 (比如使用 [monolog/monolog](https://packagist.org/packages/monolog/monolog)),可创建一个实现 Mix\Log\LoggerHandlerInterface 接口的 Handler 类,在内部使用 monolog 处理不同级别的日志,然后在 manifest.php 中把 Handler 类传入 MultiHandler::class 的依赖配置即可。