应使用sharedscripts确保postrotate脚本在匹配多个日志文件时仅执行一次,避免重复reload导致服务抖动;需将其置于postrotate前、与通配符路径配合,并添加systemctl is-active校验。

用 sharedscripts 优化大规模日志切分,核心是避免重复执行 reload 或 restart 类操作,尤其当一个配置块匹配多个日志文件时——比如 Nginx 的 /var/log/nginx/*.log 会同时匹配 access.log 和 error.log,若不加控制,postrotate 会被触发两次,造成服务反复重载、CPU 瞬时升高、甚至短暂不可用。
sharedscripts 的作用机制
它让整个 {} 配置块内所有匹配到的日志文件,在完成全部轮转动作(重命名、压缩、清理)后,只统一执行一次 postrotate ... endscript 脚本,而不是每个文件各执行一遍。
没有 sharedscripts 时:
→ access.log 切割 → 执行 systemctl reload nginx
→ error.log 切割 → 再执行一次 systemctl reload nginx
有 sharedscripts 时:
→ access.log 和 error.log 全部处理完 → 只执行一次 reload
Zynq‑7000 / Zynq UltraScale+ 硬件调试技能。适用于 Xilinx Zynq(Cortex‑A9/A53 + FPGA)Linux 环境,调试 I2C、I2S、UART、GPIO 等外设。包括设备树配置、内核驱动、用户空间调试工具、交叉编译和常见问题排查,支持 PetaLinux 开发。
正确配置 sharedscripts 的关键点
-
必须和 postrotate 搭配使用:单独写
sharedscripts无意义,它只为postrotate(或prerotate)生效 -
写在 postrotate 之前:顺序不能颠倒,标准写法是
sharedscripts→postrotate→endscript -
多个路径共用一个块才有效:例如把
/var/log/nginx/access.log和/var/log/nginx/error.log放在同一配置块里,或直接用通配符/var/log/nginx/*.log -
不要跨服务混用:Nginx 和 Tomcat 日志不应写进同一个
{}块,否则 reload 逻辑会冲突;应按服务拆分配置文件
典型高效配置示例
以 Nginx 为例,保存为 /etc/logrotate.d/nginx:
/var/log/nginx/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 644 nginx nginx
sharedscripts
postrotate
if systemctl is-active --quiet nginx; then
systemctl reload nginx > /dev/null 2>&1
fi
endscript
}
这个配置能同时处理所有 .log 文件,且无论匹配几个,reload 只跑一次。加上 is-active 判断,还能防止服务未运行时出错。
验证是否真正生效
别只看配置,要实测:
- 用
logrotate -d /etc/logrotate.d/nginx查看 debug 输出,确认 “running postrotate script” 只出现一次 - 手动强制执行:
logrotate -f /etc/logrotate.d/nginx,再检查systemctl status nginx的最近 reload 时间戳,应只有单次更新 - 观察系统负载:
uptime或htop,对比开启/关闭sharedscripts时的 CPU 尖峰幅度

















