-
创建自定义日志驱动
你需要在应用的 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 扩展已经安装并启用。