TP6.0 自定义日志驱动
2023-02-25 18:20:00 时间
1. 新增日志通道配置
// 其它日志通道配置
'log' => [
// 日志记录方式
'type' => app\driver\Log::class,
// 日志保存目录
'path' => app()->getRootPath() . 'log',
],
2. 自定义日志驱动类
自定义日志驱动,需要实现 think\contract\LogHandlerInterface
接口
参考TP6.0官方文档完全开发手册 : https://www.kancloud.cn/manual/thinkphp6_0/1037616#_377
interface LogHandlerInterface
{
/**
* 日志写入接口
* @access public
* @param array $log 日志信息
* @return bool
*/
public function save(array $log): bool;
}
<?php
declare (strict_types = 1);
namespace app\driver;
use think\facade\Log as LogFacade;
use think\contract\LogHandlerInterface;
/**
* 自定义日志驱动
*/
class Log implements LogHandlerInterface
{
/**
* 构造方法
*/
public function __construct()
{
// 获取日志通道配置信息
$this->config = LogFacade::getChannelConfig('log');
}
/**
* 保存日志
* @param array $data
*/
public function save(array $data): bool
{
foreach ($data as $type => $item ) {
foreach ( $item as $value ) {
$this->write($type, ['type' => $type,'value' => $value]);
}
}
return true;
}
/**
* 执行写入文件
* @param [type] $type
* @param [type] $data
* @return void
*/
public function write($type, $data)
{
$path = implode('/', [$this->config['path'], $type . '.log']);
if ( ! file_exists(dirname($path)) ) mkdir(dirname($path), 0777, true);
$content = '------------ ' . date('Y-m-d H:i:s') . ' ------------' . PHP_EOL . PHP_EOL . var_export($data, true) . PHP_EOL . PHP_EOL;
file_put_contents($path, $content, FILE_APPEND);
}
}
3. 写入日志
use think\facade\Log;
Log::channel('log')->record('测试日志信息');
相关文章
- 记一次“雪花算法”造成的生产事故的排查记录
- 两万字盘点那些被玩烂了的设计模式
- 如何在React导航栏实现搜索功能
- 前端常用的数据可视化工具库
- Go 要违背初心吗?新提案:手动管理内存
- 如何避免由 Web 字体引起的布局偏移
- 你问这谁会啊?ThreadLocal 父子线程之间该如何传递数据?
- 我是怎么定位线上问题的?
- 从头开始进行CUDA编程:线程间协作的常见技术
- Golang 的 “omitempty” 关键字详解
- Amazing!巧妙构建页面结构的 3D Visualization
- 动动嘴就能写代码?网友怒怼:哪位高管想当然了!
- C语言该怎么进阶?你学会了吗?
- 聊聊一致性Hash算法代码实现
- Go 语言如何实现字符串切片反转函数
- PROGENy: Pathway RespOnsive GENes for activity inference(一)
- Go 真实项目的性能案例研究
- 重大发现,AQS加锁机制竟然跟Synchronized有惊人的相似
- 【Go微服务】一文带你玩转ProtoBuf
- 通过一个插件来了解Neovim的Winbar属性