ThinkPHP 在 CentOS 上的日志管理实践
一 定位与保留策略
日志默认目录为项目根目录下的 runtime/log/,常见按天生成文件(如:YYYY-mm-dd.log)。框架自 5.1.6+ 起支持通过文件通道的 max_files 限制保留文件数量,避免无限增长;从 5.1.15+ 可开启 json 格式便于分析。示例配置(config/log.php):
参考配置:
return [
'default' => 'file',
'channels' => [
'file' => [
'type' => 'file',
'path' => '', // 默认 runtime/log
'level' => ['error','info'],
'max_files' => 30,
'json' => true,
],
],
];
提示:确保运行用户对 runtime/log 具备写权限;JSON 格式便于后续接入 ELK/Graylog 等系统。
二 使用 logrotate 对 ThinkPHP 日志做系统级轮转
/var/www/your-project/runtime/log/*.log {
daily
rotate 30
compress
missingok
notifempty
create 644 www-data www-data
copytruncate
dateext
dateformat -%Y%m%d
}
关键点说明:
三 关联日志的轮转与监控
/var/log/php-fpm/*.log {
daily
rotate 7
compress
missingok
notifempty
create 640 root adm
sharedscripts
postrotate
if [ -f /run/php-fpm/php-fpm.pid ]; then
kill -USR2 `cat /run/php-fpm/php-fpm.pid`
fi
endscript
}
/var/log/nginx/*.log {
daily
rotate 7
compress
missingok
notifempty
create 640 nginx adm
postrotate
if [ -f /run/nginx.pid ]; then
kill -HUP `cat /run/nginx.pid`
fi
endscript
}
四 集中化与多行堆栈处理
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/www/your-project/runtime/log/*.log
multiline.pattern: '^-'
multiline.negate: true
multiline.match: after
encoding: utf-8
output.elasticsearch:
hosts: ["your-es:9200"]
说明:以行首 “-----” 或 “Caused by:” 作为多行起始的合并策略,可显著提升堆栈可读性。五 常见问题与快速处置