thinkphp6 日志同步到redis

  • 创建自定义日志驱动

    你需要在应用的 app/log 目录下创建一个新的日志驱动类(自己自定义)

// app/log/RedisHandler.php  
  
namespace app\log;  
use Redis;
use think\contract\LogHandlerInterface;
use think\Exception;

class RedisHandler implements LogHandlerInterface
{
    protected $redis;
    protected $type = 'redis';
    public function __construct(array $config = [])
    {
        $this->redis = new Redis();
        $this->redis->connect($config['host'], $config['port']);
        if (isset($config['password'])) {
            $this->redis->auth($config['password']);
        }
        if (isset($config['select'])) {
            $this->redis->select($config['select']);
        }
        if (isset($config['timeout'])) {
            $this->redis->setOption(Redis::OPT_READ_TIMEOUT, $config['timeout']);
        }
    }
    
    public function save(array $log) :bool
    {
        if(empty($log)) return true;
        // 格式化日志信息
        $message = json_encode($log,JSON_UNESCAPED_UNICODE);
        // 你可以选择存储到Redis的List, Set, Hash, String等结构中
        // 这里以List为例
        $this->redis->rPush('log:'.date("Ymd"), $message);
        return true;
    }
}

- 步骤 2: 配置日志驱动
接下来,你需要在应用的配置文件 config/log.php 中添加或修改日志配置,以使用你的自定义 Redis 驱动。

<?php

// +----------------------------------------------------------------------
// | 日志设置
// +----------------------------------------------------------------------
return [
    // 默认日志记录通道
    'default'      => 'redis',
    // 日志记录级别
    'level'        => [],
    // 日志类型记录的通道 ['error'=>'email',...]
    'type_channel' => [],
    // 关闭全局日志写入
    'close'        => false,
    // 全局日志处理 支持闭包
    'processor'    => null,
    'channel'     => true,
    // 日志通道列表
    'channels'     => [
        'file' => [
            // 日志记录方式
            'type'           => 'File',
            // 日志保存目录
            'path'           => '',
            // 单文件日志写入
            'single'         => false,
            // 独立日志级别
            'apart_level'    => [],
            // 最大日志文件数量
            'max_files'      => 0,
            // 使用JSON格式记录
            'json'           => false,
            // 日志处理
            'processor'      => null,
            // 关闭通道日志写入
            'close'          => false,
            // 日志输出格式化
            'format'         => '[%s][%s] %s',
            // 是否实时写入
            'realtime_write' => false,
        ],
        // 其它日志通道配置
        'redis'   =>  [
            // 驱动方式
            'type'   =>  \app\log\RedisHandler::class,
            'host' => '127.0.0.1',
            'port' => 6379,
            'password' => 123456,
            'select' => 0,
        ],
    ],

];

注意

  • 确保你的 Redis 服务器已经正确配置,并且 PHP 的 Redis 扩展已经安装并启用。
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值