zl程序教程

您现在的位置是:首页 >  其他

当前栏目

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('测试日志信息');