Nginx enable php errors

nginx / php-fpm error logging

I’m trying to figure out where the PHP errors are going in my setup. I’m running nginx as the reverse proxy to PHP-FPM, but I’m not seeing the various E_NOTICE or E_WARNING messages my app is producing. The only reason I know they’re happening is failed responses and NewRelic catching stack traces. Here’s the logging config: nginx.conf

proxy_intercept_errors on; fastcgi_intercept_errors on; 
error_reporting = E_ALL display_errors = Off display_startup_errors = Off log_errors = On log_errors_max_len = 1024 ignore_repeated_errors = Off ignore_repeated_source = Off report_memleaks = On track_errors = On error_log = syslog 
[global] error_log = /var/log/php-fpm/fpm-error.log [www] access.log = /var/log/php-fpm/access.log access.format = "%t \"%m %r%Q%q\" %s %dms %Mkb %C%%" catch_workers_output = yes php_flag[display_errors] = on php_admin_flag[log_errors] = true 
:syslogtag, contains, "php" /var/log/php-fpm/error.log 

I’ve configured PHP to log to syslog, however FPM has no syslog function so it’s logging to a file. I don’t really care where the errors end up, just that they end up somewhere. Any clues on how I might get this to work?

I would try make errors display first (in a test.php file you could manually trigger an error), then put them in a file and so on. . Could be errors triggered are from cli, thus using a different php.ini

Did you try this? php_admin_value[error_log] = /var/log/php-fpm/www-error.log php_admin_flag[log_errors] = on

4 Answers 4

Your php-fpm.conf file is not set up to send errors to syslog. See below for an example of how to do this.

; Error log file ; If it's set to "syslog", log is sent to syslogd instead of being written ; in a local file. ; Note: the default prefix is /var ; Default Value: log/php-fpm.log error_log = syslog ; syslog_facility is used to specify what type of program is logging the ; message. This lets syslogd specify that messages from different facilities ; will be handled differently. ; See syslog(3) for possible values (ex daemon equiv LOG_DAEMON) ; Default Value: daemon ;syslog.facility = daemon ; syslog_ident is prepended to every message. If you have multiple FPM ; instances running on the same server, you can change the default value ; which must suit common needs. ; Default Value: php-fpm ;syslog.ident = php-fpm ; Log level ; Possible Values: alert, error, warning, notice, debug ; Default Value: notice ;log_level = notice 

Are you sure about your assumption for the rsyslog.conf? That is, are you sure all such syslog messages are tagged with lower-case «php»?

Читайте также:  To do list app javascript

Try setting syslog.facility to something like local2 (or local1, or local7) and replacing your rsyslog.conf config-line accordingly:

local2.* /var/log/php-fpm/error.log 

When you’re using php-fpm, it appears to override the php.ini settings.

The logging most likely needs to be configured in . /www.conf .

I uncommented these lines in order to grab the PHP logs.

php_admin_value[error_log] = /var/log/php-errors.log php_admin_flag[log_errors] = on 

The webserver user and group can also be found in this file under lines similar to this (may differ between unix socket & proxy configuration).

listen.owner = www-data listen.group = www-data 

Then it’s just a matter of creating the file and configuring it properly.

touch /var/log/php-errors.log chmod 644 /var/log/php-errors.log chgrp www-data /var/log/php-errors.log chown www-data /var/log/php-errors.log 

I believe the log level is still used from php-fpm.conf so you may also need to check this.

Thanks. It works. But adding this line log_level = error would cause an error and stop php-fpm from launching. My php-fpm version is 7.2 .

to get php-fpm errors in nginx error log you need:

as for nginx: it s enough just basic config

# cat default | grep -v "#" server < listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name _; index index.html; location / < try_files $uri $uri/ =404; >location ~ \.php$ < include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php7.0-fpm.sock; >> 

as for php-fpm the main setting is

basically it s enough. but to be on the safe side i would suggest to put the following block in php-fpm config(/etc/php/7.0/fpm/php.ini) :

[PHP] . error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT display_errors = Off display_startup_errors = On log_errors = On log_errors_max_len = 1024 ignore_repeated_errors = Off ignore_repeated_source = Off report_memleaks = On track_errors = Off html_errors = On . 

after that all php stack traces will be in

# tail /var/log/nginx/error.log 2023/06/20 23:37:06 [error] 20307#20307: *1 FastCGI sent in stderr: "PHP message: PHP Parse error: syntax error, unexpected '"asd"' (T_CONSTANT_ENCAPSED_STRING) in /var/www/html/php1.php on line 2" while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /php1.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "localhost" 2023/06/20 23:48:40 [error] 20307#20307: *5 FastCGI sent in stderr: "PHP message: PHP Parse error: syntax error, unexpected '"asd"' (T_CONSTANT_ENCAPSED_STRING) in /var/www/html/php1.php on line 2" while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /php1.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "localhost" 2023/06/21 00:18:17 [error] 20307#20307: *7 FastCGI sent in stderr: "PHP message: PHP Parse error: syntax error, unexpected '"asd"' (T_CONSTANT_ENCAPSED_STRING) in /var/www/html/php1.php on line 2" while reading response header from upstream, client: 127.0.0.1, server: _, request: "GET /php1.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "localhost:4545" 

if you want to see php stack traces not in nginx erorr file but instead in a separate file you need to add error_log setting that is

error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT display_errors = Off display_startup_errors = On log_errors = On error_log = /var/log/php-errors.log log_errors_max_len = 1024 ignore_repeated_errors = Off ignore_repeated_source = Off report_memleaks = On track_errors = Off html_errors = On 

also very important to create /var/log/php-errors.log manually and set proper permisssions because php-fpm wont do that and will continue to transfer error to nginx. so

# touch /var/log/php-errors.log # chown www-data.www-data /var/log/php-errors.log # systemctl restart php7.0-fpm 

after that nginx error log /var/log/nginx/error.log will be empty but all php-errors will be in /var/log/php-errors.log

Источник

Как включить вывод ошибок PHP

Хостинг-провайдеры нередко отключают или блокируют вывод всех ошибок и предупреждений. Такие ограничения вводятся не просто так. Дело в том, что на рабочих серверах крайне не рекомендуется держать ошибки в открытом доступе. Информация о неисправностях может стать «наживкой» для злоумышленников.

При этом в процессе разработки сайтов и скриптов, очень важно отслеживать возникающие предупреждения. Знать о сбоях и неисправностях также важно и системным администраторам — это позволяет предотвратить проблемы на сайте или сервере.

Самый оптимальный вариант — не просто скрыть показ ошибок, но и настроить запись о них в логах. Это позволит отслеживать предупреждения и не подвергать сервер угрозе.

В статье мы расскажем, как включить и отключить через .htaccess вывод ошибок php, а также двумя другими способами — через скрипт PHP и через файл php.ini.

Обратите внимание: в некоторых случаях изменение настроек вывода возможно только через обращение в техническую поддержку хостинга.

Через .htaccess

Перейдите в каталог сайта и откройте файл .htaccess.

Вариант 1. Чтобы включить вывод, добавьте следующие строки:

php_flag display_startup_errors on php_flag display_errors on php_flag html_errors on

Чтобы отключить ошибки PHP htaccess, введите команду:

php_flag display_startup_errors off php_flag display_errors off php_flag html_errors off

Также выключить .htaccess display errors можно командой:

php_flag display_startup_errors off php_flag display_errors off php_flag html_errors off php_value docref_root 0 php_value docref_ext 0

Через логи PHP

Если вам нужно проверить или выключить ошибки только в определенных файлах, это можно сделать с помощью вызова PHP-функций.

Вариант 1. Чтобы включить вывод, используйте команду error_reporting. В зависимости от типа ошибок, которые вы хотите увидеть, подставьте нужное значение. Например, команда для вывода всех ошибок будет выглядеть так:

А для всех типов, исключая тип Notice, так:

error_reporting(E_ALL & ~E_NOTICE)

Чтобы отключить вывод, введите команду:

Чтобы отключить логирование повторяющихся ошибок, введите:

# disable repeated error logging php_flag ignore_repeated_errors on php_flag ignore_repeated_source on

Вариант 2. Чтобы проверить конкретный кусок кода, подойдет команда ниже. В зависимости от типа ошибок, которые вы хотите увидеть, в скобках подставьте нужное значение. Например, команда для вывода всех ошибок будет выглядеть так:

ini_set('display_errors', 'On') error_reporting(E_ALL)

После этого в консоли введите:

ini_set('display_errors', 'Off')

Вариант 3. Ещё один из вариантов подключения через скрипт:

php_flag display_startup_errors on php_flag display_errors on
php_flag display_startup_errors off php_flag display_errors off

Вариант 4. Чтобы настроить вывод с логированием через конфигурацию веб-сервера, введите:

  • для Apache — ErrorLog «/var/log/apache2/my-website-error.log» ,
  • для Nginx — error_log /var/log/nginx/my-website-error.log .

Подробнее о других аргументах читайте в документации на официальном сайте php.net.

Через файл php.ini

Настроить отслеживание также можно через файл php.ini. Этот вариант подойдет, когда отображение или скрытие ошибок нужно настроить для всего сайта или кода. Обратите внимание: возможность настройки через файл php.ini есть не у всех, поскольку некоторые хостинг-провайдеры частично или полностью закрывают доступ к файлу.

Вариант 1. Если у вас есть доступ, включить вывод можно командой:

После этого нужно перезагрузить сервер:

sudo apachectl -k graceful

Вариант 2. Чтобы включить вывод, используйте команду error_reporting. В зависимости от типа ошибок, которые вы хотите увидеть, после знака = подставьте нужное значение. Например, команда для вывода всех ошибок будет выглядеть так:

error_reporting = E_ALL display_errors On

После ввода перезагрузите сервер:

sudo apachectl -k graceful

Чтобы скрыть отображение, во второй строке команды укажите Оff вместо On:

Теперь вы знаете, как настроить не только через PHP и php.ini, но и через htaccess отображение ошибок.

Источник

Оцените статью