雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

TP6.0 自定义日志驱动

2024-09-09 16

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;}
<?phpdeclare (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('测试日志信息');
更新于:9天前
赞一波!

文章评论

全部评论