TP6.0 自定义日志驱动
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('测试日志信息');
本站发布的内容若侵犯到您的权益,请邮件联系站长删除,我们将及时处理!
从您进入本站开始,已表示您已同意接受本站【免责声明】中的一切条款!
本站大部分下载资源收集于网络,不保证其完整性以及安全性,请下载后自行研究。
本站资源仅供学习和交流使用,版权归原作者所有,请勿商业运营、违法使用和传播!请在下载后24小时之内自觉删除。
若作商业用途,请购买正版,由于未及时购买和付费发生的侵权行为,使用者自行承担,概与本站无关。