ThinkPHP 日志系统配置、使用、自定义及优化

以下是关于 ThinkPHP 日志系统的详细说明,涵盖配置、使用、自定义及优化等方面:


1. 日志配置(config/log.php)

return [
    'default'      => 'file', // 默认日志通道
    'channels'     => [
        'file' => [
            'type'       => 'file', // 文件日志
            'path'       => '', // 日志路径(默认runtime/log)
            'level'      => ['info', 'error'], // 记录级别
            'max_files'  => 30, // 最大日志文件数
            'json'       => false, // 是否JSON格式
        ],
        'db'   => [
            'type'       => 'database', // 数据库日志
            'table'      => 'logs', // 表名
            'connection' => null, // 数据库连接配置
        ],
    ],
];

2. 日志级别

  • 从低到高debuginfonoticewarningerrorcriticalalertemergency
  • 设置 level 可过滤低于该级别的日志(如设为 error 则忽略 debuginfo)。

3. 记录日志

use think\facade\Log;

// 基础用法
Log::write('手动记录', 'info');
Log::info('用户登录', ['user_id' => 1]);

// 上下文数据(数组自动转JSON)
Log::error('支付失败', ['order_id' => 1001, 'reason' => '余额不足']);

// 快速方法
Log::warning('磁盘空间不足');
Log::emergency('系统崩溃!');

4. 日志文件

  • 路径runtime/log/YYYY-mm-dd.log(默认按天分割)。
  • 文件名自定义:配置中设置 path' => 'runtime/log/app.log' 可固定文件名。
  • 滚动切割:通过 max_files 限制文件数量,避免磁盘占满。

5. 自定义日志通道

5.1 写入数据库
// 配置数据库连接后
Log::channel('db')->info('订单创建', ['order_id' => 2001]);
5.2 发送到邮件(需扩展)
'email' => [
    'type'       => 'email',
    'receivers'  => ['admin@example.com'],
    'subject'    => '系统错误报警',
],

6. 高级用法

  • 日志格式化:继承 think\log\driver\File 重写 format 方法。
  • 实时监控:结合 tail -f runtime/log/2025-07-07.log 查看实时日志。
  • 性能优化:高频日志建议使用 Log::batch(true) 开启批量写入。

7. 常见问题

  • 日志不写入:检查目录权限(runtime/log 需可写)。
  • 日志过大:调整 max_files 或按业务分通道记录。
  • 敏感信息:避免在日志中记录密码等敏感数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值