在 config/log.php
中设置日志通道、级别、路径等参数,如:
return [
'default' => 'file',
'channels' => [
'file' => [
'type' => 'file',
'path' => runtime_path('logs'), // 日志存储路径(可自定义)
'level' => ['info', 'error'], // 记录级别
'max_files' => 30, // 保留天数/文件数
'json' => false, // 是否JSON格式
],
// 可添加数据库、远程等通道
],
];
使用 think\facade\Log
记录不同级别日志:
use think\facade\Log;
Log::info('用户登录', ['user_id' => 1]); // 信息日志
Log::error('支付失败', ['order_id' => 1001]); // 错误日志
runtime/logs
目录下的日志文件。grep
、awk
筛选日志,或 tail -f
实时查看。runtime/logs
下的旧日志文件。cron
定期清理,例如每天凌晨删除7天前的日志:# 编辑定时任务
crontab -e
# 添加以下内容(每天0点执行)
0 0 * * * find /path/to/project/runtime/logs -type f -mtime +7 -exec rm -f {} \;
logrotate
工具,配置按天/大小轮转日志,避免单个文件过大。rsyslog
或自定义驱动实现。runtime/logs
目录权限为 640
,仅允许应用写入。Log::batch(true)
开启批量写入。参考来源: