ThinkPHP的日志配置主要通过config/log.php文件(TP6+)或config/app.php(TP5)完成,核心参数包括:
default指定默认日志驱动(如file、database、email等);channels定义各通道的具体参数,如file通道的path(日志路径,默认runtime/log)、level(记录级别,如['error', 'warning'])、max_files(最大文件数,避免磁盘占满)、json(是否输出JSON格式);debug→info→notice→warning→error→critical→alert→emergency,可通过level过滤低级别日志。think\facade\Log类快速记录日志,支持链式调用,例如:use think\facade\Log;
Log::info('用户登录成功', ['user_id' => 1]); // 记录info级别日志,带上下文
Log::error('数据库连接失败', ['error' => 'Connection refused']); // 记录error级别日志
Log类的静态方法直接记录,如Log::write('手动记录日志', 'debug')(实时写入)、Log::record('缓存数据', 'notice')(先存内存,后续统一写入)。runtime/log/目录下,按日期分割(如2025-09-29.log),可使用cat、less、tail等命令查看:tail -f runtime/log/2025-09-29.log # 实时监控最新日志
less runtime/log/error.log # 查看错误日志
php think log命令,可查看所有日志文件内容或指定级别日志:php think log # 查看所有日志
php think log --level=error # 仅查看error级别日志
runtime/log/目录下的旧日志文件,或使用truncate命令清空文件内容(避免删除文件导致权限问题):rm -rf runtime/log/*.log # 删除所有日志文件
truncate -s 0 runtime/log/*.log # 清空所有日志文件内容
.log文件,然后添加到Cron:# 创建脚本/usr/local/bin/clear_thinkphp_log
echo '#!/bin/bash\nfind /path/to/project/runtime/log -mtime +7 -name "*.log" -exec rm -rf {} \;' > /usr/local/bin/clear_thinkphp_log
chmod +x /usr/local/bin/clear_thinkphp_log
# 添加Cron任务(每天凌晨2点执行)
echo '0 2 * * * /usr/local/bin/clear_thinkphp_log' | sudo tee -a /etc/crontab
logrotate实现日志轮转(压缩、删除旧日志),步骤如下:
/etc/logrotate.d/thinkphp:/path/to/project/runtime/log/*.log {
daily # 每天轮转
rotate 7 # 保留7天
missingok # 文件不存在不报错
notifempty # 空文件不轮转
compress # 压缩旧日志(gzip)
delaycompress # 延迟压缩(避免当天日志未写完)
sharedscripts # 所有日志处理完再执行脚本
postrotate # 轮转后执行的命令(如重启服务)
/bin/kill -USR1 $(cat /var/run/php/php8.1-fpm.pid) 2>/dev/null || true
endscript
}
sudo logrotate -d /etc/logrotate.d/thinkphp(模拟运行,查看是否有错误);sudo logrotate -f /etc/logrotate.d/thinkphp(立即执行)。file通道外,可配置其他驱动,如:
// config/log.php
'channels' => [
'db' => [
'type' => 'database',
'table' => 'logs', // 数据库表名
'connection' => 'mysql', // 数据库连接配置(需提前配置)
],
];
使用时通过Log::channel('db')->info('订单创建成功', ['order_id' => 1001])写入。'channels' => [
'email' => [
'type' => 'email',
'receivers' => ['admin@example.com'], // 接收人
'subject' => '系统错误报警', // 邮件主题
],
];
配置后,error级别日志会自动发送邮件。tail -f命令实时查看日志变化,或结合grep过滤关键信息:tail -f runtime/log/2025-09-29.log | grep 'error' # 只看error日志
Log::batch(true)),减少IO操作;敏感信息(如密码、手机号)需过滤后再记录。以上方法覆盖了Ubuntu下ThinkPHP日志的配置、记录、查看、清理及高级管理需求,可根据项目规模和实际场景选择合适的方式。