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过滤低级别日志。thinkfacadeLog类快速记录日志,支持链式调用,例如:use thinkfacadeLog;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_logecho '#!/bin/bashnfind /path/to/project/runtime/log -mtime +7 -name "*.log" -exec rm -rf {} ;' > /usr/local/bin/clear_thinkphp_logchmod +x /usr/local/bin/clear_thinkphp_log# 添加Cron任务(每天凌晨2点执行)echo '0 2 * * * /usr/local/bin/clear_thinkphp_log' | sudo tee -a /etc/crontablogrotate实现日志轮转(压缩、删除旧日志),步骤如下:/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 || trueendscript}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' => ['[email protected]'], // 接收人'subject' => '系统错误报警',// 邮件主题],];配置后,error级别日志会自动发送邮件。tail -f命令实时查看日志变化,或结合grep过滤关键信息:tail -f runtime/log/2025-09-29.log | grep 'error'# 只看error日志Log::batch(true)),减少IO操作;敏感信息(如密码、手机号)需过滤后再记录。以上方法覆盖了Ubuntu下ThinkPHP日志的配置、记录、查看、清理及高级管理需求,可根据项目规模和实际场景选择合适的方式。