First of all, since it was mentioned in the comments, we should differntiate the php error log from a custom application log:
The php error log logs errors of a certain level (notices, errors, warnings depending on your error_reporting() settings) while interpreting your php files. That means when you are trying to use an array key which was not set before a warning would be generated and either printed to the screen or logged to your php error log file.
A custom application logger on the other side logs custom messages which might contain warnings and errors regarding the application logic and which are able to be handled by the application.
When we compare the following two code examples:
<?php
error_reporting(E_ALL|E_STRICT);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', sys_get_temp_dir() . '/php_error.log');
updateUser($_POST['user_id']);
// Assuming $_POST['user_id'] was not set the above lines would produce a notice in your php_error.log stating the use of an undefined index 'user_id'
?>
Against:
// Instantiate your own logger or a 3rd party logger
$myLogger = new Logger(sys_get_temp_dir() . '/application.log');
if (!array_key_exists('user_id', $_POST)) {
$myLogger->error('Cannot update user since user_id was not set');
// Handle the error in the UI accordingly
header('Location: 404.php');
die();
}
updateUser($_POST['user_id']);
?>
For me personally it makes sense to separate these two types of errors in different log files: The php errors are usually a result of code which does not handle all imaginable cases (i.e. a user removes the hidden user_id field from a form manually) and are a hint for yourself that you should change your code to avoid the same error next time.
The second piece of code handles the exactly same use case but you considered this case while writing the code and the application is able to react somehow.
No matter if you decide pick a 3rd party logger or write your own: Think about using one which fulfils the PRS-3 logging standard to be able to make it exchangable when you i.e. decide to switch from file based logging to a database based logging mechanism. By doing so you won't have to change a lot of code when you decide to switch your loggers since the methods and general usage is standardised.
When writing your own logger, consider the following points:
- Locking and unlocking your log file while writing to it
- Log rotation (daily, weekly, monthly)
- Deletion of old log files
- Like stated above think about implementing PSR-3