温馨提示×

如何监控CentOS PHP错误日志

小樊
37
2025-11-29 22:01:33
栏目: 编程语言

监控 CentOS 上的 PHP 错误日志

一 确认日志路径与配置

  • 先明确 PHP 的日志写入位置,常见有三类:
    • PHP-FPM 错误日志:通常为 /var/log/php-fpm/error.log(多池环境可能还有 /var/log/php-fpm/www.log 等)。
    • Apache 错误日志:通常为 /var/log/httpd/error_log(PHP 运行在 mod_php 时,语法/启动错误常写入此处)。
    • PHP 内置错误日志:由 php.inierror_log 指定,例如 /var/log/php_errors.log
  • 建议的 php.ini 关键配置(生产环境):
    • error_reporting = E_ALL
    • display_errors = Off
    • log_errors = On
    • error_log = /var/log/php_errors.log
  • Web 服务器日志(便于关联请求与错误):
    • Apache:在 /etc/httpd/conf/httpd.conf 中设置 ErrorLog /var/log/httpd/error_logCustomLog /var/log/httpd/access_log combined
    • Nginx:在 /etc/nginx/nginx.conf 中设置 error_log /var/log/nginx/error.log; access_log /var/log/nginx/access.log;
  • 验证配置是否生效:
    • 查看 CLI 与 FPM 的生效配置:分别执行 php -i | grep error_logphp-fpm -i | grep error_log
    • 触发一条可控错误(如调用未定义函数)并确认日志是否写入目标文件。

二 命令行快速监控与排查

  • 实时查看日志尾部:
    • 查看 PHP-FPM 日志:tail -f /var/log/php-fpm/error.log
    • 查看 Apache 错误日志:tail -f /var/log/httpd/error_log
  • 关键字检索(减少缓冲延迟):
    • 例如:grep --line-buffered ‘error|Warning|Fatal’ /var/log/php-fpm/error.log
  • 按时间定位:
    • 例如:grep “2025-11-29” /var/log/php-fpm/error.log
  • 若 PHP 错误写入了 Web 服务器错误日志,可联合查看访问与错误:
    • tail -f /var/log/httpd/error_logtail -f /var/log/httpd/access_log
  • systemd 场景(如服务日志聚合):
    • 查看 httpd 单元日志:journalctl -u httpd -f

三 自动化分析与告警方案

  • 轻量分析与日报:
    • 使用 Logwatch 生成日志分析报告并通过邮件发送(适合日常巡检):
      • 安装:sudo yum install logwatch
      • 运行示例:sudo logwatch --output mail --mailto your-email@example.com
  • 安全与滥用拦截:
    • 使用 fail2ban 监控日志并自动封禁恶意来源(示例为监控 PHP-FPM 错误日志中的可疑频繁报错):
      • 安装:sudo yum install fail2ban
      • 配置 /etc/fail2ban/jail.local
        • [DEFAULT] bantime = 600; findtime = 600; maxretry = 3
        • [php-fpm] enabled = true; filter = php-fpm; action = iptables-multiport[name=PHP, port=“http,https”, protocol=tcp"]; logpath = /var/log/php-fpm/error.log
      • 启动:sudo systemctl start fail2ban && sudo systemctl enable fail2ban
  • 集中化日志与可视化:
    • 使用 ELK Stack(Elasticsearch + Logstash + Kibana) 收集、解析与展示 PHP 日志,并在 Kibana 中配置告警规则(适合中大型环境与多维分析)。

四 日志轮转与容量管理

  • 使用 logrotate 对 PHP 与 Web 服务日志进行按日轮转、压缩与保留,避免磁盘被占满:
    • 示例(/etc/logrotate.d/php 与 /etc/logrotate.d/httpd):
      • /var/log/php_errors.log /var/log/php-fpm/.log /var/log/httpd/.log {
      • daily; missingok; rotate 7; compress; delaycompress; notifempty; create 0644 apache apache; sharedscripts; postrotate
      • systemctl reload httpd > /dev/null 2>&1 || true; systemctl reload php-fpm > /dev/null 2>&1 || true;
      • endscript }
  • 建议将轮转周期与保留天数(如 7 天)纳入变更与容量评估流程。

0