要在Nginx和PHP-FPM环境下正确记录PHP错误日志,需要进行以下几个配置步骤:
编辑PHP-FPM配置文件(通常位于/etc/php/{version}/fpm/php.ini
或/etc/php/{version}/fpm/pool.d/www.conf
):
; 确保错误日志记录已开启
log_errors = On
; 设置错误日志文件路径
error_log = /var/log/php_errors.log
; 错误报告级别(根据需求调整)
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
; 显示错误(开发环境设为On,生产环境设为Off)
display_errors = Off
在PHP-FPM的池配置文件(如/etc/php/{version}/fpm/pool.d/www.conf
)中:
; 确保捕获输出
catch_workers_output = yes
; 设置访问日志(可选但推荐)
access.log = /var/log/php-fpm/$pool.access.log
; 设置慢日志(可选)
slowlog = /var/log/php-fpm/$pool.log.slow
request_slowlog_timeout = 10s
在Nginx的站点配置文件中,确保正确传递PHP错误:
server {
# ...其他配置...
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php{version}-fpm.sock;
# 确保错误被传递
fastcgi_intercept_errors on;
# 可选:设置自定义错误日志
error_log /var/log/nginx/php_errors.log;
}
# 错误页面处理
error_page 500 502 503 504 /error50x.html;
location = /error50x.html {
root /usr/share/nginx/html;
internal;
}
}
创建日志文件并设置适当权限:
sudo touch /var/log/php_errors.log
sudo chown www-data:www-data /var/log/php_errors.log
sudo chmod 664 /var/log/php_errors.log
sudo systemctl restart php{version}-fpm
sudo systemctl restart nginx
创建一个测试PHP文件:
<?php
// 测试错误日志
error_log("This is a test error message");
trigger_error("This is a user-generated error", E_USER_WARNING);
nonexistent_function();
?>
检查日志文件是否记录了这些错误:
tail -f /var/log/php_errors.log
按日期分割日志:可以使用logrotate或PHP的error_log
指令配合日期函数实现
不同级别日志分开记录:可以通过自定义错误处理函数实现
Syslog集成:可以将错误发送到系统日志
error_log = syslog
PHP-FPM状态页(用于监控):
location /php-status {
access_log off;
allow 127.0.0.1;
deny all;
include fastcgi_params;
fastcgi_pass unix:/var/run/php/php{version}-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
通过以上配置,您应该能够在Nginx+PHP-FPM环境中正确记录PHP错误日志。