Php fpm error reporting



PHP fpm and cli error log configuration

PHP FPM

First of all we need to enable option catch_workers_output for fpm.

catch_workers_output boolean
Redirect worker stdout and stderr into main error log. If not set, stdout and stderr will be redirected to /dev/null according to FastCGI specs. Default value: no.

/usr/local/etc/php-fpm.d/www.conf (in my configuration)

Or simply edit and save the file manually to uncomment line starting with ;catch_workers_output .

Then we need to configure log file names and locations.

Access log

If you want or need to activate access log at php level:

access.log string
The access log file. Default value: not set

  • access.log = /var/log/php/fpm-access.log

Or simply edit and save the file manually to uncomment line starting with ;access.log .

You will have this kind of output:

Error log

Of course in production we do not want to display errors to users:

Or simply edit and save the file manually to uncomment line starting with ;php_flag[display_errors] .

Then we must enable error log and define the error log file location :

  • php_admin_value[error_log] = /var/log/php/fpm-error.log
  • php_admin_flag[log_errors] = on

Or simply edit and save the file manually to uncomment lines starting with ;php_admin_value[error_log] and ;php_admin_flag[log_errors] .

You will have this kind of output:

You also could change log level:

log_level string
Error log level. Possible values: alert, error, warning, notice, debug. Default value: notice.

Important

Log files must have correct access rights (owner) and must exist:

PHP CLI

To enable php CLI errors, we need to add these lines into the (cli) php.ini file.

This configuration is for production not for debug or development.

Conclusion

Using the given configuration you should have those logs:

Do NOT forget to enable log rotation, you will have:

Share on

PHP fpm and cli error log configuration was published on February 20, 2017 .

Источник

A rapid way to set up PHP FPM error reporting & real-time solutions

by Jilu Joseph | May 23, 2019

PHP FPM handler can boost the website performance even on high traffic.

Sometimes, websites using PHP FPM show unexpected errors. And, the users may not have a clue on the underlying reason.

Fortunately, PHP fpm error reporting gives real-time details on the causes of the error. But, to make use of this we need to turn on error reporting for the website.

At Bobcares, we often get requests to fix PHP FPM errors as part of our Server Management Services.

Today, we’ll see how our Support Engineers set up PHP FPM error reporting and fix the related errors.

Importance of PHP FPM error reporting

PHP FPM error logging provides a simple but efficient solution for logging all errors into a log file. Also, the information they contain will give exact details of errors and the amount of time spent on tracking the root causes of errors.

The entries in the PHP FPM error logs look like.

Luckily, it is very easy to troubleshoot after analyzing the PHP-FPM error log and our Support Engineers found that this error occurs due to the values of pm.min/max_spare_servers and pm.start_servers. Then we increased these two values in /etc/php-fpm.d/www.conf.

Similarly, another example of entries in the PHP FPM error logs.

From the error log, we could identify that this error happens when pm.max_children setting reached its threshold value and our Support Engineers increased this value of pm.max_children in the PHP-FPM configuration file.

However, only a proper configuration of PHP FPM error reporting will provide useful entries to help fix the root cause of errors.

How we set up PHP FPM error reporting.

Now, let’s see how our Support Engineers set up PHP FPM error logging on servers.

To configure error logging for PHP-FPM,

1. Firstly, we need to configure log file names and location.

By default, we’re using www.conf pool config file or find php-fpm.conf or www.conf depending on what version of PHP-FPM you have installed. Here, we took /etc/php/7.0/fpm/pool.d/www.conf as an example.

2. So, we edit /etc/php/7.0/fpm/pool.d/www.conf file and uncomment “ catch_workers_output=yes»

3. At last, we restart php-fpm service.

How we nailed the errors related to PHP FPM error reporting

From our experience in managing server, we’ve seen that many customers had issues related to PHP FPM error logging. Let’s take a look at the top problems and how we fix them.

Improper configuration settings

Recently, one of our customers had an issue PHP FPM error logging. He couldn’t find anything in the error log after enabled FPM error reporting.

Then, our Support Engineers found that he set up PHP-FPM error log in the wrong configuration file.

Therefore, we found the exact file location by using the following command.

Next, we edited /etc/php/7.0/fpm/php-fpm.conf and properly configured it.

That fixed the problem.

Incorrect permission/missing log file

Sometimes, PHP FPM error logging may not work as we expect even if we set up the right configuration. This can happen due to missing log files or lack of write permissions for a webserver on the log file.

For example, if the permission of error log fpm-php.www.log is incorrect, the error logging will not work properly. The same thing happens in the case of missing log files.

When a customer reported problems with error logging we executed the following command to verify the files. But, files were missing as per the logs below.

Then our Support Engineers created the directory and log file fpm.log. And, then set up the right ownership.

This is how we fixed the error.

Читайте также:  Что такое error 997

[Having trouble while setting up PHP FPM error reporting? We’ll fix it for you.]

Conclusion

In short, PHP FPM error logging provides a simple but efficient solution for logging all errors into a log file. Today, we saw how our Support Engineers set up PHP FPM error reporting and solved related issues.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

Источник

How to enable error reporting in nginx php config

I have been trying for three days now to enable error reporting in PHP. I have gotten by for a while using the ini_set(‘display errors’ 1); function until I tried to connect to a DB; it didn’t work. Now, I have enabled error_reporting , display_startup_errors , log_errors without any effect on error reporting. I have changed all five config files (the development ini, production ini, the php.ini file(s) located in php/7.0/cli, php/7.0/fpm, and even the one in apache2 (even though I am running nginx)

I am beginning to doubt my own abilities, any assistance is greatly appreciated.

EDIT: I have used the ini_set function described above in my files, and it worked up until I tried to connect to a DB. I have confirmed that I’ve enabled error reporting for the php.ini file described in the phpinfo() function directory path. No effect whatsoever.

4 Answers 4

Because no one particularily gave away the answer, I will just have to post it myself.

I found the error.log file (which indeed is logging all errors on my Nginx server) in this directory: /var/log/nginx/error.log

Hopefully this may help others using Nginx as well, but I still do not understand why the **** the errors aren’t showing up in the browser. I think it is Nginx’s nature to make everything quite complicated.

Perhaps I should develop using Apache and then port it into Nginx when I have more experience — just some thoughts for others who are getting into this as well.

I just wanted to give an update on this: Since upgrading from PHP 7.0.2

Error Reporting Itself

ini_set(‘display_errors’, 1); or display_errors

Simply allows PHP to output errors — useful for debugging, highly recommended to disable for production environments. It often contains information you’d never want users to see.

error_reporting(E_ALL); or error_reporting

Simply sets exactly which errors are shown.

Setting one or the other will not guarantee that errors will be displayed. You must set both to actually see errors on your screen.

As for setting this up permanently inside your PHP config, the default for error_reporting is E_ALL &

E_DEPRECATED. That said, this variable should not need changed. See here:

As for displaying errors, see here:

Set the config value of «display_errors» to either stderr or stdout , depending on your need.

Just change these variables inside of your php.ini file and you’ll be golden. Make absolutely sure both display_errors and error_reporting is set to a satisfactory value. Just setting error_reporting will not guarantee that you see the errors you’re looking for!

Error Reporting Works Everywhere Except When Connecting To My DB!

If you see errors everywhere you need to except in the Database Connection, you just need to do some error catching. If it’s PDO, do something like this:

Just a snippet from my framework. Of course you’ll have to change it to your liking, but you should be able to get the general idea there. They key is this part here:

I Still Don’t See The Error

If you’ve done both of what I’ve listed here and still have trouble, your problem has nothing to do with enabling error reporting. The code provided will show you the error with a Database Connection itself, and inside of PHP code. You must have a completely different issue if this has not shown you an error you’re chasing.

You’ll likely need to be a bit more descriptive on exactly what you’re chasing, and what you’re expecting to see.

Источник

display_errors for php5-fpm not working with nginx

I am running nginx with php5-fpm and want to enable the display_errors . I am running a virtual host, so please help in making a way to enable display_errors , display_startup_errors .

I tried modifying /etc/php5/fpm/php.ini .

Is it require to have multiple ini files for each different virtual host, does vhost makes any difference for php configuration ?

I am also trying set_ini() , but it is not showing any effect. And I restarted nginx and php5-fpm after making changes in php.ini file.

5 Answers 5

The php.ini does nothing for php-fpm.

If you are using php-fpm: You must provide the configuration change in the fpm pool config associated with your web application. Where these are located depends on your system. The probably locations are:

  • /etc/php-fpm.d/mydomain.conf (if things have been set up neatly)
  • /etc/php-fpm.conf (if you are only using one conf for php-fpm)

Your config paths are different from mine, so poke around to see what you have in there. Don’t make changes in /etc/php-fpm.conf if a suitable conf exists in /etc/php-fpm.d/ .

If you are not using php-fpm: Update php.ini with the correct configuration.

Correct your configuration: In the configuration shown in the question, you have uncommented documentation rather than provided the correct settings. You had better undo those changes, because PHP won’t understand them.

The correct lines for php-fpm are:

The correct lines for normal php are:

Advice: Do not use these options in a production environment. Best wishes.

Читайте также:  Внутренняя ошибка сервиса error details внутренняя ошибка сервиса

Источник

error_reporting

(PHP 4, PHP 5, PHP 7, PHP 8)

error_reporting — Задаёт, какие ошибки PHP попадут в отчёт

Описание

Функция error_reporting() задаёт значение директивы error_reporting во время выполнения. В PHP есть много уровней ошибок. Используя эту функцию, можно задать уровень ошибок времени выполнения скрипта, которые попадут в отчёт. Если необязательный аргумент error_level не задан, error_reporting() вернёт текущее значение уровня протоколирования ошибок.

Список параметров

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

Доступные константы уровней ошибок и их описания приведены в разделе Предопределённые константы.

Возвращаемые значения

Возвращает старое значение уровня error_reporting либо текущее значение, если аргумент error_level не задан.

Список изменений

Версия Описание
8.0.0 error_level теперь допускает значение null.

Примеры

Пример #1 Примеры использования error_reporting()

// Выключение протоколирования ошибок
error_reporting ( 0 );

// Включать в отчёт простые описания ошибок
error_reporting ( E_ERROR | E_WARNING | E_PARSE );

// Включать в отчёт E_NOTICE сообщения (добавятся сообщения о
// непроинициализированных переменных или ошибках в именах переменных)
error_reporting ( E_ERROR | E_WARNING | E_PARSE | E_NOTICE );

// Добавлять сообщения обо всех ошибках, кроме E_NOTICE
error_reporting ( E_ALL &

// Добавлять в отчёт все ошибки PHP
error_reporting ( E_ALL );

// Добавлять в отчёт все ошибки PHP
error_reporting (- 1 );

// То же, что и error_reporting(E_ALL);
ini_set ( ‘error_reporting’ , E_ALL );

Примечания

Если передать -1 , будут отображаться все возможные ошибки, даже если в новых версиях PHP добавятся уровни или константы. Поведение эквивалентно передаче константы E_ALL .

Смотрите также

User Contributed Notes 27 notes

If you just see a blank page instead of an error reporting and you have no server access so you can’t edit php configuration files like php.ini try this:

— create a new file in which you include the faulty script:

( E_ALL );
ini_set ( «display_errors» , 1 );
include( «file_with_errors.php» );
?>

— execute this file instead of the faulty script file

now errors of your faulty script should be reported.
this works fine with me. hope it solves your problem as well!

Under PHP 8.0, error_reporting() does not return 0 when then the code uses a @ character.

= $array [ 20 ]; // error_reporting() returns 0 in php =8

The example of E_ALL ^ E_NOTICE is a ‘bit’ confusing for those of us not wholly conversant with bitwise operators.

If you wish to remove notices from the current level, whatever that unknown level might be, use &

//.
$errorlevel = error_reporting ();
error_reporting ( $errorlevel &

E_NOTICE );
//. code that generates notices
error_reporting ( $errorlevel );
//.
?>

^ is the xor (bit flipping) operator and would actually turn notices *on* if they were previously off (in the error level on its left). It works in the example because E_ALL is guaranteed to have the bit for E_NOTICE set, so when ^ flips that bit, it is in fact turned off. &

(and not) will always turn off the bits specified by the right-hand parameter, whether or not they were on or off.

The error_reporting() function won’t be effective if your display_errors directive in php.ini is set to «Off», regardless of level reporting you set. I had to set

to keep no error reporting as default, but be able to change error reporting level in my scripts.
I’m using PHP 4.3.9 and Apache 2.0.

In php7, what was generally a notice or a deprecated is now a warning : the same level of a mysql error … unacceptable for me.

I do have dozen of old projects and I surely d’ont want to define every variable which I eventually wrote 20y ago.

So two option: let php7 degrade my expensive SSDs writing Gb/hours or implement smthing like server level monitoring ( with auto_[pre-ap]pend_file in php.ini) and turn off E_WARNING

Custom overriding the level of php errors should be super handy and flexible …

This article refers to these two reporting levels:

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

What is the difference between those two levels?

Please update this article with a clear explanation of the difference and the possible use cases.

E_NOTICE integer value is 6135

If you want to see all errors in your local environment, you can set your project URL like «foo.com.local» locally and put that in bootstrap file.

if ( substr ( $_SERVER [ ‘SERVER_NAME’ ], — 6 ) == ‘.local’ ) <
ini_set ( ‘display_errors’ , 1 );
ini_set ( ‘error_reporting’ , E_ALL );
// or error_reporting(E_ALL);
>
?>

If you are using the PHP development server, run from the command line via `php -S servername:port`, every single error/notice/warning will be reported in the command line itself, with file name, and line number, and stack trace.

So if you want to keep a log of all the errors even after page reloads (for help in debugging, maybe), running the PHP development server can be useful.

Some E_STRICT errors seem to be thrown during the page’s compilation process. This means they cannot be disabled by dynamically altering the error level at run time within that page.

The work-around for this was to rename the file and replace the original with a error_reporting() call and then a require() call.

Ex, rename index.php to index.inc.php, then re-create index.php as:

( E_STRICT | E_NOTICE ));
require( ‘index.inc.php’ );
?>

That allows you to alter the error reporting prior to the file being compiled.

I discovered this recently when I was given code from another development firm that triggered several E_STRICT errors and I wanted to disable E_STRICT on a per-page basis.

see more information about php 5.3 deprecated errors

I had the problem that if there was an error, php would just give me a blank page. Any error at all forced a blank page instead of any output whatsoever, even though I made sure that I had error_reporting set to E_ALL, display_errors turned on, etc etc. But simply running the file in a different directory allowed it to show errors!

Turns out that the error_log file in the one directory was full (2.0 Gb). I erased the file and now errors are displayed normally. It might also help to turn error logging off.

To expand upon the note by chris at ocproducts dot com. If you prepend @ to error_reporting(), the function will always return 0.

( E_ALL );
var_dump (
error_reporting (), // value of E_ALL,
@ error_reporting () // value is 0
);
?>

this is to show all errors for code that may be run on different versions

for php 5 it shows E_ALL^E_STRICT and for other versions just E_ALL

if anyone sees any problems with it please correct this post

Note that E_NOTICE will warn you about uninitialized variables, but assigning a key/value pair counts as initialization, and will not trigger any error :
( E_ALL );

$foo = $bar ; //notice : $bar uninitialized

$bar [ ‘foo’ ] = ‘hello’ ; // no notice, although $bar itself has never been initialized (with «$bar = array()» for example)

$bar = array( ‘foobar’ => ‘barfoo’ );
$foo = $bar [ ‘foobar’ ] // ok

$foo = $bar [ ‘nope’ ] // notice : no such index
?>

This is very useful to remember when setting error_reporting levels in httpd.conf:

Use the table above or:

( «error_reporting» , E_YOUR_ERROR_LEVEL );
echo ini_get ( «error_reporting» );
?>

To get the appropriate integer for your error-level. Then use:

php_admin_value error_reporting YOUR_INT

I want to share this rather straightforward tip as it is rather annoying for new php users trying to understand why things are not working when the error-level is set to (int) «E_ALL» = 0.

Maybe the PHP-developers should make ie error_reporting(«E_ALL»); output a E_NOTICE informative message about the mistake?

To enable error reporting for *ALL* error messages including every error level (including E_STRICT, E_NOTICE etc.), simply use:

error_reporting() has no effect if you have defined your own error handler with set_error_handler()

[Editor’s Note: This is not quite accurate.

E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR and E_COMPILE_WARNING error levels will be handled as per the error_reporting settings.

All other levels of errors will be passed to the custom error handler defined by set_error_handler().

Zeev Suraski suggests that a simple way to use the defined levels of error reporting with your custom error handlers is to add the following line to the top of your error handling function:

It might be a good idea to include E_COMPILE_ERROR in error_reporting.

If you have a customer error handler that does not output warnings, you may get a white screen of death if a «require» fails.

Example:
( E_ERROR | E_WARNING | E_PARSE );

function myErrorHandler ( $errno , $errstr , $errfile , $errline ) <
// Do something other than output message.
return true ;
>

$old_error_handler = set_error_handler ( «myErrorHandler» );

require «this file does not exist» ;
?>

To prevent this, simply include E_COMPILE_ERROR in the error_reporting.

( E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR );
?>

I always code with E_ALL set.
After a couple of pages of
= (isset( $_POST [ ‘username’ ]) && !empty( $_POST [ ‘username’ ])).
?>

I made this function to make things a little bit quicker. Unset values passed by reference won’t trigger a notice.

function test_ref (& $var , $test_function = » , $negate = false ) <
$stat = true ;
if(!isset( $var )) $stat = false ;
if (!empty( $test_function ) && function_exists ( $test_function )) <
$stat = $test_function ( $var );
$stat = ( $negate ) ? $stat ^ 1 : $stat ;
>
elseif( $test_function == ’empty’ ) <
$stat = empty( $var );
$stat = ( $negate ) ? $stat ^ 1 : $stat ;
>
elseif (! function_exists ( $test_function )) <
$stat = false ;
trigger_error ( » $test_function () is not a valid function» );
>
$stat = ( $stat ) ? true : false ;
return $stat ;
>
$a = » ;
$b = ’15’ ;

test_ref ( $a , ’empty’ , true ); //False
test_ref ( $a , ‘is_int’ ); //False
test_ref ( $a , ‘is_numeric’ ); //False
test_ref ( $b , ’empty’ , true ); //true
test_ref ( $b , ‘is_int’ ); //False
test_ref ( $b , ‘is_numeric’ ); //false
test_ref ( $unset , ‘is_numeric’ ); //false
test_ref ( $b , ‘is_number’ ); //returns false, with an error.
?>

error_reporting() may give unexpected results if the @ error suppression directive is used.

@include ‘config.php’ ;
include ‘foo.bar’ ; // non-existent file
?>

config.php
( 0 );
?>

will throw an error level E_WARNING in relation to the non-existent file (depending of course on your configuration settings). If the suppressor is removed, this works as expected.

Alternatively using ini_set(‘display_errors’, 0) in config.php will achieve the same result. This is contrary to the note above which says that the two instructions are equivalent.

Only display php errors to the developer.

if( $_SERVER [ ‘REMOTE_ADDR’ ]== «00.00.00.00» )
<
ini_set ( ‘display_errors’ , ‘On’ );
>
else
<
ini_set ( ‘display_errors’ , ‘Off’ );
>
?>

Just replace 00.00.00.00 with your ip address.

Creating a Custom Error Handler

set_error_handler(«customError»,E_ALL);
function customError($errno, $errstr)
<
echo «Error: [$errno] $errstr
«;
echo «Ending Script»;
die();
>

In phpinfo() error reporting level display like a bit (such as 4095)

Maybe it is a simply method to understand what a level set on your host
if you are not have access to php.ini file

= ini_get ( ‘error_reporting’ );
while ( $bit > 0 ) <
for( $i = 0 , $n = 0 ; $i $bit ; $i = 1 * pow ( 2 , $n ), $n ++) <
$end = $i ;
>
$res [] = $end ;
$bit = $bit — $end ;
>
?>

In $res you will have all constants of error reporting
$res[]=int(16) // E_CORE_ERROR
$res[]=int(8) // E_NOTICE
.

Источник

Оцените статью
toolgir.ru
Adblock
detector