在 CentOS 上开启 PHP 日志,主要取决于你使用的是 PHP-FPM 还是 Apache + mod_php。下面分情况说明,适用于 CentOS 7 / 8 / Stream。
一、确认 PHP 运行方式
先确认 PHP 是以哪种方式运行的:
php -v
ps -ef | grep php
常见两种:
- PHP-FPM(推荐,Nginx / Apache 都常用)
- mod_php(Apache 老方式)
二、PHP-FPM(最常见)
1️⃣ 开启 PHP 错误日志
编辑 PHP 配置文件:
vim /etc/php.ini
确保以下配置存在并取消注释:
display_errors = Off
log_errors = On
error_reporting = E_ALL
error_log = /var/log/php/php_error.log
✅ 生产环境一定要
display_errors = Off
2️⃣ 创建日志目录并设置权限
mkdir -p /var/log/php
chown -R apache:apache /var/log/php # Apache
# 或
chown -R nginx:nginx /var/log/php # Nginx
chmod 755 /var/log/php
3️⃣ PHP-FPM 错误日志(进程级)
编辑 PHP-FPM 配置:
vim /etc/php-fpm.conf
或:
vim /etc/php-fpm.d/www.conf
确认:
php_admin_value[error_log] = /var/log/php/php_fpm_error.log
php_admin_value[log_errors] = On
4️⃣ 重启 PHP-FPM
systemctl restart php-fpm
三、Apache + mod_php
1️⃣ 修改 php.ini
vim /etc/php.ini
log_errors = On
error_log = /var/log/php/php_error.log
2️⃣ Apache 错误日志(补充)
PHP 错误也会写入 Apache 日志:
tail -f /var/log/httpd/error_log
3️⃣ 重启 Apache
systemctl restart httpd
四、Nginx + PHP-FPM
Nginx 本身不处理 PHP,PHP 错误在 php-fpm 日志 中。
查看 Nginx 错误日志:
tail -f /var/log/nginx/error.log
五、验证是否生效
创建一个测试文件:
<?php
error_log("PHP log test");
undefined_function();
访问该页面,然后查看日志:
tail -f /var/log/php/php_error.log
六、常见问题
❌ 日志不生成?
- 目录权限不对
- SELinux 未放行
SELinux 排查:
setenforce 0 # 临时关闭测试
若解决,需配置 SELinux:
semanage fcontext -a -t httpd_log_t "/var/log/php(/.*)?"
restorecon -Rv /var/log/php
七、总结(最常用)
✅ CentOS + PHP-FPM 推荐配置
log_errors = On
error_log = /var/log/php/php_error.log
mkdir /var/log/php
chown nginx:nginx /var/log/php
systemctl restart php-fpm
如果你愿意,可以告诉我:
- ✅ CentOS 版本
- ✅ Nginx / Apache
- ✅ PHP 版本
我可以给你 精确到路径 的配置方案。
