ThinkPHP 6.1 需自定义 JsonFile 日志驱动实现标准 JSON 输出:继承 File 类、重写 write() 方法,组装含时间戳、级别、消息等字段的数组并 json_encode,配置中设 'format' => '' 禁用默认格式化。

ThinkPHP 6.1 默认日志是文本格式(如 2024-01-01 12:00:00 [info] Hello world),若需输出为标准 JSON 格式(例如用于 ELK、Fluentd 或统一日志平台),需自定义日志驱动并重写日志写入逻辑。
启用自定义日志驱动
ThinkPHP 6.1 支持通过配置指定日志驱动类。你需要新建一个继承 think\log\driver\File 的类,并覆盖 write() 方法,将日志内容序列化为 JSON。
- 在
app\common\log\driver\JsonFile.php创建新驱动类(路径可自定义,确保命名空间正确) - 该类需实现
write()方法,把日志数据组装为数组后用json_encode()输出 - 注意处理中文、特殊字符和时间格式,推荐使用
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
编写 JSON 日志驱动类
示例代码如下(保存为 app\common\log\driver\JsonFile.php):
namespace app\common\log\driver;
<p>use think\log\driver\File;
use think\facade\Log;</p><p>class JsonFile extends File
{
protected function write($message, $type = 'info', $data = [])
{
$logData = [
'timestamp' => date('c'),
'level' => strtoupper($type),
'message' => is_string($message) ? $message : var_export($message, true),
'context' => $data,
'channel' => Log::getChannel(),
'runtime' => round(microtime(true) - THINK_START_TIME, 4),
];</p><pre class="brush:php;toolbar:false;"> // 过滤不可 JSON 编码的值(如 resource、Closure)
array_walk_recursive($logData, function (&$item) {
if (is_object($item) || is_resource($item)) {
$item = '[object ' . get_class($item) . ']';
}
});
$json = json_encode($logData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($json === false) {
$json = '{"error":"json_encode_failed","raw_message":' . json_encode($message) . '}';
}
return parent::write($json, $type, $data);
}}
立即学习“PHP免费学习笔记(深入)”;
配置使用 JSON 驱动
修改 config/log.php,将默认驱动指向你写的类:
'default' => 'json',
'drivers' => [
'json' => [
'type' => 'app\common\log\driver\JsonFile',
'format' => '', // 空字符串禁用默认格式化,避免干扰 JSON
'realtime_write'=> true,
'file_size' => 1024 * 1024 * 10, // 10MB
'path' => runtime_path('log/') . date('Ym') . '/',
'apart_level' => ['error', 'sql'],
'max_files' => 30,
],
],注意:'format' => '' 很关键,否则父类会额外拼接前缀(如时间、级别),破坏 JSON 结构。
验证与注意事项
启动请求后检查日志文件内容是否为合法 JSON 行(每行一条完整 JSON 对象)。常见问题包括:
- 日志目录权限不足导致写入失败 → 检查
runtime/log/是否可写 - 多进程并发写入造成 JSON 文件损坏 → 启用
'realtime_write' => true并确保磁盘 I/O 稳定 - SQL 日志或异常堆栈含非法字符 → 上述驱动已做基础过滤,复杂对象建议提前简化
- 若需每行一个 JSON(方便日志采集器解析),当前方案已满足;不需要换行符或额外分隔符



















