(PHP 4, PHP 5, PHP 7, PHP 
error_log — Отправляет сообщение об ошибке заданному обработчику ошибок
Описание
error_log(
string $message,
int $message_type = 0,
?string $destination = null,
?string $additional_headers = null
): bool
Список параметров
-
message -
Сообщение об ошибке, которое должно быть логировано.
-
message_type -
Определяет куда отправлять ошибку.
Возможны следующие значения:Типы журналов error_log()
0 Сообщение messageотправляется в системный регистратор PHP, используя
механизм логирования операционной системы, или файл, в зависимости от значения директивы
error_log
в конфигурационном файле. Это значение по умолчанию.1 Сообщение messageотправляется электронной почтой на адрес, установленный в параметре
destination. Это единственный тип сообщения, где используется четвёртый параметр
additional_headers.2 Больше не используется. 3 messageприменяется к указанному в
destinationфайлу. Перенос строки автоматически не добавляется в конец
message.4 Сообщение messageотправляется напрямую в обработчик
логера SAPI. -
destination -
Назначение. Устанавливается в зависимости от параметра
message_type. -
additional_headers -
Дополнительные заголовки. Используется, когда значение параметра
message_type
—1.
Данный тип сообщения использует ту же внутреннюю функцию, что и
mail().
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Если message_type равен нулю, функция всегда возвращает true,
независимо от того, может ли ошибка логироваться или нет.
Список изменений
| Версия | Описание |
|---|---|
| 8.0.0 |
Параметр destination иadditional_headers теперь допускают значение null.
|
Примеры
Пример #1 Примеры использования error_log()
<?php
// Отправляет уведомление посредством серверного лога, если мы не можем
// подключиться к базе данных.
if (!Ora_Logon($username, $password)) {
error_log("База данных Oracle недоступна!", 0);
}// Уведомить администратора по электронной почте, если невозможно выделить ресурсы для FOO
if (!($foo = allocate_new_foo())) {
error_log("Большая проблема, мы выпали из FOO!", 1,
"operator@example.com");
}// другой способ вызвать error_log():
error_log("Вы ошиблись!", 3, "/var/tmp/my-errors.log");
?>
Примечания
Внимание
error_log() не является бинарно-безопасной функцией. message обрезается по null-символу.
Подсказка
message не должен содержать null-символ. Учтите, что message может передаваться в файл, по почте, в syslog и т.д. Используйте подходящую преобразующую или экранирующую функцию, base64_encode(), rawurlencode() или addslashes() перед вызовом error_log().
kevindougans at gmail dot com ¶
13 years ago
Advice to novices: This function works great along with "tail" which is a unix command to watch a log file live. There are versions of Tail for Windows too, like Tail for Win32 or Kiwi Log Viewer.
Using both error_log() and tail to view the php_error.log you can debug code without having to worry so much about printing debug messages to the screen and who they might be seen by.
Further Note: This works even better when you have two monitors setup. One for your browser and IDE and the other for viewing the log files update live as you go.
Sion ¶
4 years ago
DO NOT try to output TOO LARGE texts in the error_log();
if you try to output massive amounts of texts it will either cut of the text at about 8ooo characters (for reasonable massive strings, < 32 K characters) or (for insanely massive strings, about 1.6 million characters) totally crash without even throwing an error or anything (I even put it in a try/catch without getting any result from the catch).
I had this problem when I tried to debug a response from a wp_remote_get(); all of my error_log() worked as they should, except for ONE of them... (-_-)
After about a day of debugging I finally found out why & that's why I type this.
Apparently the response contained a body with over 1.6 million chars (or bytes? (whatever strlen() returns)).
If you have a string of unknown length, use this:
$start_index = 0;
$end_index = 8000;
error_log( substr( $output_text , $start_index , $end_index ) );
frank at booksku dot com ¶
16 years ago
Beware! If multiple scripts share the same log file, but run as different users, whichever script logs an error first owns the file, and calls to error_log() run as a different user will fail *silently*!
Nothing more frustrating than trying to figure out why all your error_log calls aren't actually writing, than to find it was due to a *silent* permission denied error!
i dot buttinoni at intandtel dot com ¶
15 years ago
Be carefull. Unexpected PHP dies when 2GByte of file log reached (on systems having upper file size limit).
A work aorund is rotate logs :)
php at kennel17 dot NOSPAM dot co dot uk ¶
17 years ago
It appears that the system log = stderr if you are running PHP from the command line, and that often stderr = stdout. This means that if you are using a custom error to both display the error and log it to syslog, then a command-line user will see the same error reported twice.
Anonymous ¶
20 years ago
when using error_log to send email, not all elements of an extra_headers string are handled the same way. "From: " and "Reply-To: " header values will replace the default header values. "Subject: " header values won't: they are *added* to the mail header but don't replace the default, leading to mail messages with two Subject fields.
<?php
error_log
("sometext", 1, "zigzag@my.domain",
"Subject: FoonFrom: Rizzlas@my.domainn");?>
---------------%<-----------------------
To: zigzag@my.domain
Envelope-to: zigzag@my.domain
Date: Fri, 28 Mar 2003 13:29:02 -0500
From: Rizzlas@my.domain
Subject: PHP error_log message
Subject: Foo
Delivery-date: Fri, 28 Mar 2003 13:29:03 -0500
sometext
---------------%<---------------------
quoth the docs: "This message type uses the same internal function as mail() does."
mail() will also fail to set a Subject field based on extra_header data - instead it takes a seperate argument to specify a "Subject: " string.
php v.4.2.3, SunOS 5.8
russ at russtanner dot com ¶
3 years ago
You can easily filter messages sent to error_log() using "tail" and "grep" on *nix systems. This makes monitoring debug messages easy to see during development.
Be sure to "tag" your error message with a unique string so you can filter it using "grep":
In your code:
error_log("DevSys1 - FirstName: $FirstName - LastName: $Lastname");
On your command line:
tail -f /var/log/httpd/error_log | grep DevSys1
In this example, we pipe apache log output to grep (STDIN) which filters it for you only showing messages that contain "DevSys1".
The "-f" option means "follow" which streams all new log entries to your terminal or to any piped command that follows, in this case "grep".
Matthew Swift ¶
3 years ago
Relative paths are accepted as the destination of message_type 3, but beware that the root directory is determined by the context of the call to error_log(), which can change, so that one instance of error_log () in your code can lead to the creation of multiple log files in different locations.
In a WordPress context, the root directory will be the site's root in many cases, but it will be /wp-admin/ for AJAX calls, and a plugin's directory in other cases. If you want all your output to go to one file, use an absolute path.
paul dot chubb at abs dot gov dot au ¶
14 years ago
When logging to apache on windows, both error_log and also trigger_error result in an apache status of error on the front of the message. This is bad if all you want to do is log information. However you can simply log to stderr however you will have to do all message assembly:
LogToApache($Message) {
$stderr = fopen('php://stderr', 'w');
fwrite($stderr,$Message);
fclose($stderr);
}
SJL ¶
15 years ago
"It appears that the system log = stderr if you are running PHP from the command line"
Actually, it seems that PHP logs to stderr if it can't write to the log file. Command line PHP falls back to stderr because the log file is (usually) only writable by the webserver.
stepheneliotdewey at GmailDotCom ¶
15 years ago
Note that since typical email is unencrypted, sending data about your errors over email using this function could be considered a security risk. How much of a risk it is depends on how much and what type of information you are sending, but the mere act of sending an email when something happens (even if it cannot be read) could itself imply to a sophisticated hacker observing your site over time that they have managed to cause an error.
Of course, security through obscurity is the weakest kind of security, as most open source supporters will agree. This is just something that you should keep in mind.
And of course, whatever you do, make sure that such emails don't contain sensitive user data.
p dot lhonorey at nospam-laposte dot net ¶
16 years ago
Hi !
Another trick to post "HTML" mail body. Just add "Content-Type: text/html; charset=ISO-8859-1" into extra_header string. Of course you can set charset according to your country or Env or content.
EG: Error_log("<html><h2>stuff</h2></html>",1,"eat@joe.com","subject :lunchnContent-Type: text/html; charset=ISO-8859-1");
Enjoy !
eguvenc at gmail dot com ¶
14 years ago
<?php
//Multiline error log class
// ersin güvenç 2008 eguvenc@gmail.com
//For break use "n" instead 'n'
Class log {
//
const USER_ERROR_DIR = '/home/site/error_log/Site_User_errors.log';
const GENERAL_ERROR_DIR = '/home/site/error_log/Site_General_errors.log';
/*
User Errors...
*/
public function user($msg,$username)
{
$date = date('d.m.Y h:i:s');
$log = $msg." | Date: ".$date." | User: ".$username."n";
error_log($log, 3, self::USER_ERROR_DIR);
}
/*
General Errors...
*/
public function general($msg)
{
$date = date('d.m.Y h:i:s');
$log = $msg." | Date: ".$date."n";
error_log($msg." | Tarih: ".$date, 3, self::GENERAL_ERROR_DIR);
}
}
$log = new log();
$log->user($msg,$username); //use for user errors
//$log->general($msg); //use for general errors
?>
franz at fholzinger dot com ¶
18 years ago
In the case of missing your entries in the error_log file:
When you use error_log in a script that does not produce any output, which means that you cannot see anything during the execution of the script, and when you wonder why there are no error_log entries produced in your error_log file, the reasons can be:
- you did not configure error_log output in php.ini
- the script has a syntax error and did therefore not execute
daniel dot fukuda at gmail dot com ¶
13 years ago
If you have a problem with log file permission *silently*
it's best to leave error_log directive unset so errors will be written in your Apache log file for current VirtualHost.
Anonymous ¶
2 years ago
Depending on the error, you may also want to add an error 500 header, and a message for the user:
$message = 'Description of the error.';
error_log($message);
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
exit($message);
Robert Chapin ¶
4 years ago
When error_log() unexpectedly uses stdout, you should check if the php.ini value for error_log is empty in your CLI environment. Something as simple as this might restore expected behavior:
<?php ini_set('error_log', 'error_log'); ?>
kazezb at nospam dot carleton dot edu ¶
17 years ago
It appears that error_log() only logs the first line of multi-line log messages. To log a multi-line message, either log each line individually or write the message to another file.
Anonymous ¶
13 years ago
After scouring the internet for getting event logging to
work in syslog on Windows 2003, I found the following
from this post and was able to successfully get Windows
Event Viewer to log PHP errors/notices:
http://forums.iis.net/p/1159662/1912015.aspx#1913338
1. Copy the PHP 5 binaries to "C:php".
2. Right-click My Computer and select Properties to bring
up the Computer Properties dialog. Switch to the Advanced
tab and click Environment Variables. Find the system
environment variable PATH, edit it and add ";C:php"
(without the quotes) to the end.
3. Make sure that the configuration file "php.ini" resides
in the directory "C:php" and contains the correct path
settings.
4. DELETE any old "php.ini" files from "C:WINDOWS"
and other directories.
5. Open REGEDIT, navigate to the key
"HKLMSOFTWAREPHP" and DELETE the string value
"IniFilePath" from there. It is outdated and no longer
necessary!
6. Modify NTFS security permissions of the directory
"C:php" to give Read and Execute permissions to (1) the
IIS Guest Account and (2) the group IIS_WPG.
7. Modify NTFS security permissions of the directories
"C:phpsession" and "C:phpupload" to give additional
Modify permissions to (1) the IIS Guest Account and (2)
the group IIS_WPG.
8. Navigate to the registry key
"HKLMSYSTEMCurrentControlSetServicesEventlog
Application" and edit the value "CustomSD" there. Find
the substring "(D;;0xf0007;;;BG)" which Denies access to
the application event log for Builtin Guest accounts (like
the IIS Web User account) and replace this substring with
"(A;;0x3;;;BG)" which allows read and write access. Please
pay attention to leave the rest of the security string intact.
Damaging this value can have dangerous effects!
9. Create or update the registry key
"HKLMSYSTEMCurrentControlSetServicesEventlogApplication
PHP-5.2.0" (adapt the last to your version part
if necessary) with the following values:
* "EventMessageFile" (REG_EXPAND_SZ) = "C:phpphp5ts.dll"
* "TypesSupported" (REG_DWORD) = 7
Несколько вариантов как быстро организовать запись данных в лог-файл.
1
Строки текста
$log = date('Y-m-d H:i:s') . ' Запись в лог';
file_put_contents(__DIR__ . '/log.txt', $log . PHP_EOL, FILE_APPEND);
PHP
Запись в лог-файле:
2019-02-02 16:00:38 Запись в лог
2
Массивы
Если нужно записать в лог обычный массив, массив с индексами или многомерный массив, поможет функция print_r().
$array = array(
'foo' => 'bar',
'helo' => 'world',
'array' => array(1, 2)
);
$log = date('Y-m-d H:i:s') . ' ' . print_r($array, true);
file_put_contents(__DIR__ . '/log.txt', $log . PHP_EOL, FILE_APPEND);
PHP
Запись в лог-файле:
2019-02-02 16:43:27
Array
(
[foo] => bar
[helo] => world
[array] => Array
(
[0] => 1
[1] => 2
)
)
В одну строку
$array = array(
'foo' => 'bar',
'helo' => 'world',
'array' => array(1, 2)
);
$log = date('Y-m-d H:i:s') . ' ';
$log .= str_replace(array(' ', PHP_EOL), '', print_r($array, true));
file_put_contents(__DIR__ . '/log.txt', $log . PHP_EOL, FILE_APPEND);
PHP
2019-02-02 16:56:00 Array([foo] => bar[helo] => world[array] => Array([0] => 1[1] => 2))
3
Результат работы PHP скрипта
Если нужно добавить в лог результат работы PHP скрипта, помогут функции буферизации ob_start() и ob_get_clean().
ob_start();
// Вывод заголовков браузера.
foreach (getallheaders() as $name => $value) {
echo "$name: $valuen";
}
$log = date('Y-m-d H:i:s') . PHP_EOL . ob_get_clean() . PHP_EOL;
file_put_contents(__DIR__ . '/log.txt', $log, FILE_APPEND);
PHP
Запись в лог-файле:
2019-11-20 12:54:58
Host: example.com
X-HTTPS: 1
X-Forwarded-Proto: https
Connection: close
cache-control: max-age=0
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534 (KHTML, like Gecko)
sec-fetch-user: ?1
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
x-compress: null
sec-fetch-site: none
sec-fetch-mode: navigate
accept-encoding: gzip, deflate, br
accept-language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
cookie: PHPSESSID=123
4
Запись в лог ошибок PHP
Если логирование предполагает фиксацию только ошибок, то лучше писать их в общий лог PHP, подробнее на php.net.
error_reporting(E_ALL);
ini_set('error_log', __DIR__ . '/php-errors.log');
error_log('Запись в лог', 0);
PHP
[02-Feb-2019 20:18:17 Europe/Moscow] Запись в лог
06.02.2019, обновлено 11.11.2022
Другие публикации

Описание значений глобального массива $_SERVER с примерами.

phpQuery – это удобный HTML парсер взявший за основу селекторы, фильтры и методы jQuery, которые позволяют…

JSON (JavaScript Object Notation) – текстовый формат обмена данными, основанный на JavaScript, который представляет собой набор пар {ключ: значение}. Значение может быть массивом, числом, строкой и…

Протокол FTP – предназначен для передачи файлов на удаленный хост. В PHP функции для работы с FTP как правило всегда доступны и не требуется установка дополнительного расширения.

Ниже приведён список MIME-заголовков и расширений файлов.

Несколько примеров как в PHP получить информацию о домене и IP-адресе.
В этом руководстве мы расскажем о различных способах того, как в PHP включить вывод ошибок. Мы также обсудим, как записывать ошибки в журнал (лог).
Как быстро показать все ошибки PHP
Самый быстрый способ отобразить все ошибки и предупреждения php — добавить эти строки в файл PHP:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Что именно делают эти строки?
Функция ini_set попытается переопределить конфигурацию, найденную в вашем ini-файле PHP.
Display_errors и display_startup_errors — это только две из доступных директив. Директива display_errors определяет, будут ли ошибки отображаться для пользователя. Обычно директива dispay_errors не должна использоваться для “боевого” режима работы сайта, а должна использоваться только для разработки.
display_startup_errors — это отдельная директива, потому что display_errors не обрабатывает ошибки, которые будут встречаться во время запуска PHP. Список директив, которые могут быть переопределены функцией ini_set, находится в официальной документации .
К сожалению, эти две директивы не смогут отображать синтаксические ошибки, такие как пропущенные точки с запятой или отсутствующие фигурные скобки.
Отображение ошибок PHP через настройки в php.ini
Если ошибки в браузере по-прежнему не отображаются, то добавьте директиву:
display_errors = on
Директиву display_errors следует добавить в ini-файл PHP. Она отобразит все ошибки, включая синтаксические ошибки, которые невозможно отобразить, просто вызвав функцию ini_set в коде PHP.
Актуальный INI-файл можно найти в выводе функции phpinfo (). Он помечен как “загруженный файл конфигурации” (“loaded configuration file”).
Отображать ошибки PHP через настройки в .htaccess
Включить или выключить отображение ошибок можно и с помощью файла .htaccess, расположенного в каталоге сайта.
php_flag display_startup_errors on
php_flag display_errors on
.htaccess также имеет директивы для display_startup_errors и display_errors.
Вы можете настроить display_errors в .htaccess или в вашем файле PHP.ini. Однако многие хостинг-провайдеры не разрешают вам изменять ваш файл PHP.ini для включения display_errors.
В файле .htaccess также можно включить настраиваемый журнал ошибок, если папка журнала или файл журнала доступны для записи. Файл журнала может быть относительным путем к месту расположения .htaccess или абсолютным путем, например /var/www/html/website/public/logs.
php_value error_log logs/all_errors.log
Включить подробные предупреждения и уведомления
Иногда предупреждения приводят к некоторым фатальным ошибкам в определенных условиях. Скрыть ошибки, но отображать только предупреждающие (warning) сообщения можно вот так:
error_reporting(E_WARNING);
Для отображения предупреждений и уведомлений укажите «E_WARNING | E_NOTICE».
Также можно указать E_ERROR, E_WARNING, E_PARSE и E_NOTICE в качестве аргументов. Чтобы сообщить обо всех ошибках, кроме уведомлений, укажите «E_ALL & ~ E_NOTICE», где E_ALL обозначает все возможные параметры функции error_reporting.
Более подробно о функции error_reporting ()
Функция сообщения об ошибках — это встроенная функция PHP, которая позволяет разработчикам контролировать, какие ошибки будут отображаться. Помните, что в PHP ini есть директива error_reporting, которая будет задана этой функцией во время выполнения.
error_reporting(0);
Для удаления всех ошибок, предупреждений, сообщений и уведомлений передайте в функцию error_reporting ноль. Можно сразу отключить сообщения отчетов в ini-файле PHP или в .htaccess:
error_reporting(E_NOTICE);
PHP позволяет использовать переменные, даже если они не объявлены. Это не стандартная практика, поскольку необъявленные переменные будут вызывать проблемы для приложения, если они используются в циклах и условиях.
Иногда это также происходит потому, что объявленная переменная имеет другое написание, чем переменная, используемая для условий или циклов. Когда E_NOTICE передается в функцию error_reporting, эти необъявленные переменные будут отображаться.
error_reporting(E_ALL & ~E_NOTICE);
Функция сообщения об ошибках позволяет вам фильтровать, какие ошибки могут отображаться. Символ «~» означает «нет», поэтому параметр ~ E_NOTICE означает не показывать уведомления. Обратите внимание на символы «&» и «|» между возможными параметрами. Символ «&» означает «верно для всех», в то время как символ «|» представляет любой из них, если он истинен. Эти два символа имеют одинаковое значение в условиях PHP OR и AND.
error_reporting(E_ALL);
error_reporting(-1);
ini_set('error_reporting', E_ALL);
Эти три строки кода делают одно и то же, они будут отображать все ошибки PHP. Error_reporting(E_ALL) наиболее широко используется разработчиками для отображения ошибок, потому что он более читабелен и понятен.
Включить ошибки php в файл с помощью функции error_log ()
У сайта на хостинге сообщения об ошибках не должны показываться конечным пользователям, но эта информация все равно должна быть записана в журнал (лог).
Простой способ использовать файлы журналов — использовать функцию error_log, которая принимает четыре параметра. Единственный обязательный параметр — это первый параметр, который содержит подробную информацию об ошибке или о том, что нужно регистрировать. Тип, назначение и заголовок являются необязательными параметрами.
error_log("There is something wrong!", 0);
Параметр type, если он не определен, будет по умолчанию равен 0, что означает, что эта информация журнала будет добавлена к любому файлу журнала, определенному на веб-сервере.
error_log("Email this error to someone!", 1, "someone@mydomain.com");
Параметр 1 отправит журнал ошибок на почтовый ящик, указанный в третьем параметре. Чтобы эта функция работала, PHP ini должен иметь правильную конфигурацию SMTP, чтобы иметь возможность отправлять электронные письма. Эти SMTP-директивы ini включают хост, тип шифрования, имя пользователя, пароль и порт. Этот вид отчетов рекомендуется использовать для самых критичных ошибок.
error_log("Write this error down to a file!", 3, "logs/my-errors.log");
Для записи сообщений в отдельный файл необходимо использовать тип 3. Третий параметр будет служить местоположением файла журнала и должен быть доступен для записи веб-сервером. Расположение файла журнала может быть относительным путем к тому, где этот код вызывается, или абсолютным путем.
Журнал ошибок PHP через конфигурацию веб-сервера
Лучший способ регистрировать ошибки — это определить их в файле конфигурации веб-сервера.
Однако в этом случае вам нужно попросить администратора сервера добавить следующие строки в конфигурацию.
Пример для Apache:
ErrorLog "/var/log/apache2/my-website-error.log"
В nginx директива называется error_log.
error_log /var/log/nginx/my-website-error.log;
Теперь вы знаете, как в PHP включить отображение ошибок. Надеемся, что эта информация была вам полезна.
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
In PHP, errors and warnings can be logged into a file by using a php script and changing configuration of php.ini file. Two such approaches are mentioned below:
Approach 1: The error_log() function can be used to send error messages to a given file. First argument to the function is the error message to be sent. Second argument tells where to send/log the error message. In this case, second argument is set to 3, used to redirect error message to a file. Third argument is used to specify the file path of the error logging file.
Below is the implementation of the above approach:
<?php
$error_message = "This is an error message!";
$log_file = "./my-errors.log";
error_log($error_message, 3, $log_file);
?>
Output:
[20-Dec-2018 17:32:00 UTC] This is an error message!
Approach 2:
- The init_set() function allows a user to programmatically update configuration of the php.ini file.
- The ini_set(“log_errors”, TRUE) command can be added to the php script to enable error logging in php.
- The ini_set(‘error_log’, $log_file) command can be added to the php script to set the error logging file.
- Further error_log($error_message) function call can be used to log error message to the given file.
Below is the implementation of the above approach:
<?php
$error_message = "This is an error message!";
$log_file = "./my-errors.log";
ini_set("log_errors", TRUE);
ini_set('error_log', $log_file);
error_log($error_message);
?>
Output:
[20-Dec-2018 17:30:35 UTC] This is an error message!
Similar Approach: Following lines can also be added directly to php.ini to make the configuration changes permanent for every php script that logs errors and warnings.
log_errors = on error_log = ./errors.log
Note:: This approach is not highly reliable as compared to other approaches. Its better to use approach 1 as it gives flexibility of choosing different files for logging at same time without changing configuration of php.ini file.
Last Updated :
02 Jan, 2019
Like Article
Save Article
Способы реализации записи данных в лог-файлы.
Включаем вывод всех ошибок:
declare(strict_types=1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
Запись строки
$log = date('Y-m-d H:i:s') . ' Запись в лог';
file_put_contents(__DIR__ . '/log.txt', $log . PHP_EOL, FILE_APPEND);
Запись массива
$array = [
'foo' => 'bar',
'data' => [1, 2]
];
$log = date('Y-m-d H:i:s') . ' ' . print_r($array, true);
file_put_contents(__DIR__ . '/log.txt', $log . PHP_EOL, FILE_APPEND);
Запись массива одной строкой
$array = [
'foo' => 'bar',
'data' => [1, 2]
];
$log = date('Y-m-d H:i:s') . ' ';
$log .= str_replace([' ', PHP_EOL], '', print_r($array, true));
file_put_contents(__DIR__ . '/log.txt', $log . PHP_EOL, FILE_APPEND);
Результат работы PHP скрипта
ob_start();
// Вывод заголовков браузера.
foreach (get_headers('https://yandex.ru') as $name => $value) {
echo "$name: $valuen";
}
$log = date('Y-m-d H:i:s') . PHP_EOL . ob_get_clean() . PHP_EOL;
file_put_contents(__DIR__ . '/log.txt', $log, FILE_APPEND);
Результат работы скрипта можно записать в лог и таким способом:
$path = realpath(__DIR__);
$logPath = $path . '/runtime/';
try {
$command = "php $path/handler.php > {$logPath}process.log 2>&1 &";
exec($command);
} catch (Exception $exception) {
echo $exception->getMessage();
}
Файл handler.php:
echo date('Y/m/d H:i:s') . ': Сервис запущен' . PHP_EOL;
for ($i = 0; $i <= 10; $i++):
echo "Итерация: $i" . PHP_EOL;
endfor;
echo date('Y/m/d H:i:s') . ': Сервис остановлен' . PHP_EOL;
Запись в лог ошибок PHP
ini_set('error_log', __DIR__ . '/php-errors.log');
error_log('Запись ошибки в лог', 0);
// More
$logPath = __DIR__ . '/runtime';
$errorMsg = date('Y/m/d H:i:s') . ': Сообщение в лог' . PHP_EOL;
error_log($errorMsg, 3, $logPath . '/errors.log');
Простая функция
function logger($message)
{
$logPath = __DIR__ . '/runtime';
if (!is_dir($logPath)) {
mkdir($logPath, 0777, true);
}
$errorMsg = date('Y/m/d H:i:s') . ": $message" . PHP_EOL;
error_log($errorMsg, 3, $logPath . '/errors.log');
}
// Вызываем логер
logger('Ошибка получения данных в файле ' . __FILE__);
Monolog
Monolog — Логирование для PHP
use MonologLogger;
use MonologHandlerStreamHandler;
$logPath = __DIR__ . '/runtime';
$logger = new Logger('warning');
$logger->pushHandler(new StreamHandler("$logPath/warning.log", Logger::WARNING));
$logger->warning('Ошибка!', ['name' => 'John']);
Почитать по теме
here’s my log function:
You can edit the log rows by editing $maxLogs=5,
also the order to write your logs $logOrder='top'
<?php
lg('script start','start');
#Code......
lg('script end','End of code');
function lg($str,$mod='Your Log Category'){
$ts = microtime(true);
if(!defined('logTimer')){
define('logTimer',microtime(true));
}
$diff=abs(round(($ts-logTimer)*1000,2));
$maxLogs=5;
$logOrder='top';#new Logs at top
$filename = './log.txt';
$log=[];
if(!file_exists($filename)){
if(!file_put_contents($filename,json_encode($log,128))){
echo "Can’t open to write '$filename' Check Permissions";
return;
}
}else{
$c=file_get_contents($filename);
if(trim($c)==''){$c='[]';}
$log =@json_decode($c,true);
if(!is_Array($log)){$log=[];}
}
$new=['mod'=>$mod,'date'=> date('Y-m-d H:i:s')." Scripttime: ".$diff."ms",'log'=>$str];
if($logOrder=='top'){
array_unshift($log , $new);
$log=array_slice($log,0,$maxLogs);
}else{
$log[]=$new;
$log=array_slice($log,0-$maxLogs,$maxLogs);
}
$logs=json_encode($log,128);
if(!file_put_contents($filename,$logs) ){echo ("Can’t open to write '$filename' Check Permissions") ;return;}
return $str;
}
?>
The Output looks like:
[
{
"mod": "delete",
"date": "2022-08-04 13:48:02 0.33ms",
"log": "test 2"
},
{
"mod": "start",
"date": "2022-08-04 13:48:29 0ms",
"log": "test"
},
{
"mod": "delete",
"date": "2022-08-04 13:48:29 0.27ms",
"log": "test 2"
},
{
"mod": "start",
"date": "2022-08-04 13:48:34 0ms",
"log": "test"
},
{
"mod": "delete",
"date": "2022-08-04 13:48:34 0.92ms",
"log": "test 2"
}
]
Как показать ошибки PHP
Если погуглить «ошибки PHP» или «PHP errors» , то одним из первых результатов в поиске будет ссылка на документацию по функции error_reporting. Эта функция позволяет как установить уровень отчетов об ошибках PHP, так и получить текущий уровень отчетов об ошибках PHP, как определено вашей конфигурацией PHP.
Функция error_reporting принимает единственный параметр, целое число, которое указывает, какой уровень отчетности установить. Если ничего не передавать в качестве параметра, функция error_reporting просто возвращается текущий установленный уровень.
Существует длинный список возможных значений, которые можно передать в качестве параметра. Мы рассмотрим их позже.
Сейчас важно знать, что для каждого значения, которое может быть передано в качестве параметра, в PHP уже существует предопределенная константа. Так, например, константа E_ERROR имеет значение 1. Это означает, что вы можете передать 1 или E_ERROR в функцию error_reporting и получить тот же результат.
Конфигурация отчетов об ошибках
Конфигурация отчетов об ошибках Использование функции error_reporting отлично подходит, когда необходимо просто увидеть любые ошибки, связанные с фрагментом кода, над которым вы сейчас работаете.
Но конечно было бы лучше контролировать, о каких ошибках сообщается в вашей локальной среде разработки, и регистрировать их где-нибудь, чтобы иметь возможность просматривать их позже. Это можно сделать внутри файла инициализации PHP (или php.ini).
Файл php.ini отвечает за настройку всех аспектов поведения PHP. В этом файле Вы можете установить такие вещи, как объем памяти, который следует выделить для сценариев PHP, разрешить загрузку файлов и какие уровни error_reporting вы хотите для своей среды.
Если вы не уверены или не знаете, где находится файл php.ini, один из способов узнать это - создать скрипт PHP, который использует функцию phpinfo. Эта функция выведет всю информацию, относящуюся к вашему PHP.
Как вы можете видеть из моего phpinfo, мой текущий файл php.ini находится в /etc/php/7.3/apache2/php.ini. Ваш файл может иметь другое расположение.
Найдя файл php.ini, откройте его в любом редакторе и найдите раздел «Error handling and logging». Вот тут и начинается самое интересное!
Директивы сообщения об ошибках
Директивы сообщения об ошибкахПервое, что вы увидите в этом разделе, - это раздел комментариев, который включает подробное описание всех констант уровня ошибки. Далее мы будем использовать эти константы, чтобы установить уровни отчетов об ошибках.
Также эти константы задокументированы в документации по PHP.
Под этим списком находится второй список значений. Здесь показано, как установить некоторые часто используемые наборы комбинаций значений отчетов об ошибках, включая значения по умолчанию, предлагаемое значение для среды разработки и предлагаемые значения для "боевого" окружения.
; Common Values:
; E_ALL (Show all errors, warnings and notices including coding standards.)
; E_ALL & ~E_NOTICE (Show all errors, except for notices)
; E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notices and coding standards warnings.)
; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)
; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
После всех комментариев указано текущее значение вашего уровня error_reporting. Для локальной разработки я бы предложил установить его на E_ALL, что позволит видеть все ошибки.
error_reporting = E_ALL
Обычно это одна из первых вещей, которую следует сделать при настройке новой среды разработки. Таким образом, можно увидеть все сообщения об ошибках.
После директивы error_reporting вы можете установить некоторые дополнительные директивы. Как и раньше, файл php.ini включает описания каждой директивы. Ниже приведено краткое описание самых важных из них.
Директива display_errors позволяет вам устанавливать, выводить ли PHP ошибки или нет. Обычно у меня установлено значение «On»,что позволяет видеть ошибки по мере их возникновения.Директива display_startup_errors позволяет включить / выключить отображение ошибок, которые могут возникнуть во время запуска PHP. Обычно это ошибки в конфигурации PHP или веб-сервера, а не конкретно в вашем коде. Рекомендуется оставить это значение выключенным, если вы не можете устранить проблему и не уверены, что ее вызывает.Директива log_errors сообщает PHP, нужно ли записывать ошибки в файл журнала ошибок. По умолчанию он всегда включен и рекомендуется.
Остальные директивы можно оставить по умолчанию, за исключением, может быть, директивы error_log, которая позволяет указать, где регистрировать ошибки, если log_errors включен. По умолчанию он регистрирует ошибки там, где где указал ваш веб-сервер.
Настройка логирования ошибок
Настройка логирования ошибокЕсли Вы используете в качестве веб-сервера Apache, в конфигурации виртуального хоста добавьте следующее, чтобы определить местоположение журнала ошибок.
ErrorLog ${APACHE_LOG_DIR}/project-error.log
Если же Вы используете в качестве веб-сервера nginx, тогда в конфигурационный файл вашего проекта необходимо добавить следующее:
error_log /var/www/sites/logs/error.log error;
Итак, в зависимости от вашей локальной среды разработки вам может потребоваться настроить логирование в соответствии с вашими потребностями. В качестве альтернативы, если вы не можете указать журнал логирования на уровне веб-сервера, вы можете установить его на уровне php.ini.
error_log = /path/to/php.log
Стоит отметить, что в этом файле будут регистрироваться все ошибки PHP, и если вы работаете над несколькими проектами, это может быть не совсем удобно.
Поиск и исправление ошибок
Поиск и исправление ошибокЕсли вы недавно начали программировать на PHP и решили включить отчет об ошибках, будьте готовы к тому, что ваш код будет отображать множество сообщений. Вы можете увидеть некоторые вещи, которых не ожидали, и которые необходимо исправить.
Преимущество, однако, в том, что теперь, когда вы знаете, как включить все это на уровне сервера, вы можете быть уверены, что видите эти ошибки, видите когда они случаются, и исправляете их до того, как их увидят другие!
Как искать и исправлять ошибки? Да очень просто. В журнале ошибок как правило указан файл и строка кода, где произошла ошибка. Также в файле журнала ошибок может храниться вся цепочка вызовов, которая привела к возникновению ошибки.
on
May 06, 2021
The Essential Guide to PHP Error Logging
PHP has been one of the top (if not best) server-side scripting languages in the world for decades. However, let’s be honest – error logging in PHP is not the most straightforward or intuitive. It involves tweaking a few configuration options plus some playing around to get used to. Once you have everything set up and figured out (like you will after reading this post), things seem much easier, and you realize how helpful error logging can turn out to be for your application – from debugging and troubleshooting to monitoring and maintenance.
And this is why we are covering error logging in PHP in this post. We will start by revisiting the importance of logging errors in your application. We will then explore errors in PHP – their different types, and how they can be output. Next, we will look at all the error logging configurations in PHP, and understand how we can tweak these to our liking, before we see some error logging examples, and explore functions in PHP that allow us to write errors to log files. This post is a complete guide to error logging in PHP.
Here’s an outline of what we’ll be covering so you can easily navigate or skip ahead in the guide:
- Importance of Logging Errors
- PHP Error Types
- Where Can PHP Errors be Output
- Enabling and Configuring Error Reporting in PHP
- Logging Errors in PHP
- PHP’s Error Logging Functions
- error_log()
- trigger_error()
- syslog()
- set_error_handler()
- Popular PHP Logging Libraries
Importance of Logging Errors
Errors in software systems have this terrible reputation of being associated with failing things and breaking functionality. As a result, many of us often fail to recognize the importance of these loud red strings that bring our attention to faults, inconsistencies, and inaccuracies in our code – mistakes that can cost us dearly if allowed to fall through the cracks. Therefore, it is worthwhile for some of us to change our outlook towards error messages – to track, log, and organize them – and embrace their importance.
There’s a reason developers and organizations build and leverage dedicated logging systems that keep track of errors that arise throughout an application’s lifecycle. These logs provide useful information about what went wrong, when, where, and how it can be fixed.
For small-scale personal projects, it is common for developers not to feel the need to spend time setting up an effective logging system. This seems plausible because your code and end-user interactions are much more manageable for smaller projects. However, the requirement for effectively logging and maintaining errors and other information grows exponentially as your application scales. For larger applications, catering to thousands of users, it becomes unwieldy to track errors and updates across hundreds of components in real-time. Putting in place a system that can record the status of the very many events that an application’s operation entails allows organizations to maintain a clear record of their performance. This allows for more transparency and therefore ensures that no issues go unnoticed. As a result, this makes your application more reliable, easy to maintain, monitor, and debug.
Now that we are hopefully convinced that error logging is a worthwhile expedition, let us look at the different types of errors in PHP.
PHP Error Types
Broadly, there are five types of errors in PHP:
1. Fatal run-time Errors (E_ERROR)
These errors typically happen when an operation in your code cannot be performed. This leads to your code exiting. An example of a fatal error would be when you call a function that hasn’t been defined in your code, shown below:
<?php
function foo() {
echo "Function foo called.";
}
boo(); // undefined function 'boo'
?>
Error output –>
Fatal error: Uncaught Error: Call to undefined function boo() in code/my-php/index.php:5 Stack trace: #0 {main} thrown in code/my-php/index.php on line 5.
2. Warning Errors (E_WARNING)
A warning error is more gentle and less obtrusive in that it does not halt the execution. It presents a friendly reminder of something amiss in your code – a mistake that might not fail things immediately or fail anything at all but suggests a more accurate way of doing things that make your code more foolproof. These warnings can also save developers from issues that might pose a much bigger threat in the future. An example of a warning error would be when you try to include a file in PHP using an incorrect file path, as shown below:
<?php
include('filename.txt'); // arbitrary file that is not present
echo "Hello world";
?>
Error output ->
Warning: include(filename.txt): failed to open stream: No such file or directory in code/my-php/index.php on line 2
3. Parse Errors (E_PARSE)
Parse errors are also known as syntax errors as they arise from syntactical mistakes in your code. These errors are raised during the compilation of your code, making it exit before it runs. A common example of a parse error is missing a semicolon at the end of a code statement, shown below:
<?php
echo Hello world // no quotes or semicolon used
?>
Error output ->
Parse error: syntax error, unexpected 'world' (T_STRING), expecting ',' or ';' in code/my-php/index.php on line 2.
4. Notice Errors (E_NOTICE)
Notice errors are minor errors that are encountered during run-time, and just like warning errors, do not halt the execution. They usually occur when the script is attempting to access an undefined variable, for example, as shown below:
<?php
$a = 1;
$c = $a + $b; // undefined variable $b
?>
Error output ->
Notice: Undefined variable: b in code/my-php/index.php on line 3
5. User Errors (E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE)
User errors are user-defined, i.e., present a custom user-generated message raised explicitly from the code to capture a specific condition. These errors are manually raised by developers using the trigger_error function instead of the PHP engine. They are further classified as fatal, warning, and notice errors, but we’ll group them all as user errors for simplicity.
Where can PHP Errors be Output?
There are two primary places where we can have our errors presented in PHP – through inline errors and dedicated error log files.
Inline Errors
Inline errors are those that show up on your webpage in the browser or your terminal via STDOUT in a command-line environment. These errors prove to be quite useful during development – for developers to debug their code, fix issues, and get information about the overall execution. Below is an example of what these errors usually look like in the browser:
Though this proves to be super helpful for developers, you should be very careful in ensuring that these errors are not output when your application goes into production – for two reasons – end-user experience and security. You can toggle the displaying of these errors using the display_error directive in your system’s configuration. We’ll dive deeper into this in the next section.
Error Log Files
Inline errors are not persistent in memory, i.e., they are not saved anywhere and are only viewed as long as the browser or terminal session is alive. Additionally, you’ll only want to have them in a development environment. Conversely, as the theme of this post suggests, logging your errors is the more intelligent and more systematic approach towards maintaining large-scale applications. These are persistent in memory and provide information about the operation of your application across multiple components in one place, making it easier for monitoring and troubleshooting.
PHP, therefore, allows you to direct all your errors to specific log files; these files store timestamps, error stack traces, custom messages, and other helpful information about the source of the error and how to fix it. You can specify the path of your custom log file using the error_log directive of your system configuration. Here’s an example of an error log file:
You can also choose to have your errors logged to the system’s log file, usually located in – /var/log/syslog. We’ll cover this in a later section in the post.
Now let’s look at how we can configure where and how we want our errors logged.
Enabling and Configuring Error Reporting in PHP
As we discussed previously, logging in PHP is slightly less straightforward than other languages and frameworks. You might have to tweak a few options in configuration files to customize logging patterns. For example, when you install PHP on your machine, the initial configuration comes with some aspects of error logging disabled. This differs from system to system, and therefore, you should manually check these settings before getting started.
Logging Configuration Options in php.ini File
The configuration options are in the php.ini file. This file is read when PHP starts up and allows developers to play around with PHP’s functionality. Usually, this file can be found somewhere in the /etc/php directory on most Linux systems.
There are a bunch of directives (options) pertaining to the logging of errors in PHP that we can configure in this php.ini file:
- display_errors (default: 1)
Display errors are the inline errors we previously looked at. This directive can be used to good effect during development to output PHP error messages to the browser or terminal. However, for applications in production, you should likely turn this off to save your users from a poor website experience due to obscure error messages. Not only that, but this also protects you from exposing valuable information about the internals of your application as a security measure.
- display_startup_errors (default: 0)
As the name suggests, this is to output any errors that take place when PHP starts up. These usually do not provide any valuable information about your application specifically, and therefore need not be turned on.
- log_errors (default: 0)
This directive allows you to toggle the logging of errors to the specified path (in the next directive). Because this is turned off by default, it would be advisable to toggle this to 1 for recording your application’s error messages in a log file.
- error_log (default: 0)
This directive allows you to specify the path of your log file. You can also set this to “syslog” for directing all your error log messages to the system log.
- error_reporting (default: null)
The error_reporting directive allows you to customize which error levels you want reported, and which you are okay with going unreported. For example, you can use the directive as shown below to have all errors reported: error_reporting = E_ALL
- track_errors (default: 0)
This directive allows you to access the last raised error message in the $php_errormsg global variable in your code and can keep track of errors across your whole project.
After making changes to your php.ini file, you will need to restart the server for the changes to take effect.
The ini_set() Function
However, if you are unable to locate the php.ini file, or prefer overriding your project’s global configuration options, there is also an option to update these directives using the ini_set() function in your PHP code. For example, the below code can be used for customizing error reporting in your project:
<?php
// enabling error logging
ini_set('log_errors', 1);
// Customize reporting of errors
ini_set('error_reporting', E_WARNING | E_ERROR | E_PARSE | E_NOTICE);
// specify error log file path
ini_set('error_log', '/tmp/my-logs.log');
?>
The error_reporting() Function
One can also modify the error_reporting configuration option using the error_reporting() function from inside your code during run-time. As in the ini_set function, you can use bitwise operators like OR (|), AND (&), NOT (~), etc., when specifying the error levels to be reported. Below are a few examples of how this function can be used.
// Report only selected kinds of errors
error_reporting(E_ERROR | E_PARSE | E_NOTICE);
or
// Report all errors except E_WARNING
error_reporting(E_ALL & ~E_WARNING);
Now that we have got the system configurations and overall setup out of the way, let’s look at an example of how errors in your project code can be logged to files on your system.
Logging Errors in PHP
First, we will override the logging configuration parameters using the ini_set() function to enable error logging and specify the log file’s path. Then we’ll write some erroneous code to have PHP raise an error that we would like to have logged.
<?php
ini_set('log_errors', 1); // enabling error logging
ini_set('error_log', '/path/my-error-file.log'); // specifying log file path
echo $b; // undefined variable should raise error
?>
After opening the web page on our browser, let’s open the ‘my-error-file.log’ file to see if the error message was logged. Here is the log file output:
[28-Feb-2021 13:34:36 UTC] PHP Notice: Undefined variable: b in code/my-php/index.php on line 5
As you can see, our notice error was logged with a timestamp. As our code encounters more and more errors, this file will keep getting populated with corresponding timestamps. Note that we haven’t explicitly turned off display_errors, so these error messages are likely to be logged to the browser web page – something you might want to avoid during production.
This was an example of capturing errors raised by PHP in log files. Now let’s look at how we can raise and log custom error messages for our application.
PHP’s Error Logging Functions
So far, we looked at errors raised by PHP – errors about your code execution. However, oftentimes you would want to also capture custom errors, with custom error messages specific to the functioning of your application. These so-called errors might not necessarily fail your code or halt its execution, but can indicate conditions characterized as erroneous and noteworthy for your application. These can act as indications to the organization about anomalous behavior that the team might want to look into and fix.
To facilitate this, PHP provides a set of functions that we can use to actively log errors in our code.
error_log()
The most common method for actively logging errors is the error_log() function. This sends a string argument for the error message to the log file.
error_log (string $message, int $message_type=0, string $destination=?, string $extra_headers=?) : bool
It also takes many other parameters to send error messages over email or specific log files. However, for the sake of simplicity, we won’t be covering that here.
The interesting thing about this function is it logs your error message to the file specified in the configuration (or to the system log), regardless of the value of the log_errors directive. Let’s take a very simple example of logging an error when a specific condition in our code is met.
<?php
ini_set('error_log', '/path/my-error-file.log');
$a = 5;
$b = 10;
$c = $a + $b;
if ($c < 20) {
error_log("Sum is less than 20."); // logging custom error message
}
?>
Here is the output of the log file:
[28-Feb-2021 13:31:50 UTC] Sum is less than 20
Similarly, you can also log the values of variables in your code to provide additional context about your errors. Let’s see an example for that:
<?php
ini_set('error_log', '/path/my-error-file.log');
$languagesArray = array("PHP", "Python", "Node.js");
error_log("Lorem ipsum. Array data -> ".print_r($languagesArray, true));
?>
Here’s the output of the log file ->
[28-Feb-2021 13:49:28 UTC] Lorem ipsum. Array data -> Array
(
[0] => PHP
[1] => Python
[2] => Node.js
)
trigger_error()
The trigger_error() function can be used to raise a user-defined error/warning/notice. You can also specify the error type based on the condition. This allows you to customize its reporting and other behavior – for example, using an error type of E_USER_ERROR. We can cause the code to exit immediately compared to an E_USER_WARNING error.
trigger_error (string $error_msg, int $error_type=E_USER_NOTICE) : bool
The difference between trigger_error and error_log is that the former only generates a user error and depends on your system’s logging configurations to handle this error message (whether displayed or logged). error_log, on the other hand, will log your message regardless of the system’s configuration.
Here is the code for the same example we saw previously:
<?php
ini_set('log_errors', 1); // enabling error logging
ini_set('error_log', '/path/my-error-file.log'); // specifying log file path
$a = 5;
$b = 10;
$c = $a + $b;
if ($c < 20) {
trigger_error("Sum is less than 20.", E_USER_ERROR);
echo "This will not be printed!";
}
?>
This adds a similar log entry to what we saw previously, but with an error level, plus the conventional error source information (log file output below):
[01-Mar-2021 01:16:56 UTC] PHP Fatal error: Sum is less than 20. in code/my-php/index.php on line 10
syslog()
You can also choose to directly send an error message to the system’s log using the syslog() function.
syslog (int $priority, string $message) : bool
The first argument is the error’s priority level – LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_ALERT, LOG_EMERG, etc. (more about it here). The second argument is the actual message’s text. This is how the function can be used:
<?php
// opening logger connection
openlog('myApp', LOG_CONS | LOG_NDELAY | LOG_PID, LOG_USER | LOG_PERROR
); // more information about params in documentation
syslog(LOG_WARNING, "My error message!");
closelog();
?>
This should reflect in your system’s logger (usually in /var/log/syslog) as:
Mar 1 13:27:15 zsh php: My error message!
set_error_handler()
To customize the handling of all the user-defined errors throughout your code, PHP allows you to specify a custom error handler function to override the default handling of errors. This makes it easy for organizations to modify how they want their errors logged, the corresponding error messages send method, and much more. The set_error_handler() function helps with this.
set_error_handler (callable $error_handler, int $error_types=E_ALL | E_STRICT) : mixed
It takes as an argument our custom error handler function, which will define the handling of our errors, and look something like this:
handler (int $errno, string $errstr, string $errfile=?, int $errline=?, array $errcontext=?) : bool
This takes in many parameters like the error number, error string, corresponding file, etc. Let’s understand this better using the same previous example:
<?php
// custom error handler function ->
function myErrorHandler($errno, $errstr, $errfile, $errline, $errcontext){
$message = date("Y-m-d H:i:s - "); // timestamp in error message
$message .= "My Error: [" . $errno ."], " . "$errstr in $errfile on line $errline, n"; // custom error message
$message .= "Variables:" . print_r($errcontext, true) . "rn";
error_log($message, 3, "/path/my-error-file.log");
die("There was a problem, please try again."); // exit code
}
set_error_handler("myErrorHandler");
$a = 5;
$b = 10;
$c = $a + $b;
if ($c < 20) {
trigger_error("Sum is less than 20.", E_USER_WARNING);
}
echo "This will not be printed!";
?>
Here, we define a custom error handler function where we modify the error message a bit, log it, and exit the code. Then, when we use the trigger_error() function, its logging is handled by the above function, which takes care of the rest. This is what the output in the log file looks like:
2021-03-01 06:58:07 - My Error: [512], Sum is less than 20. in code/my-php/index.php on line 22,
Variables:Array
(
[a] => 5
[b] => 10
[c] => 15
)
As you can see, this can be used to fully customize error logging in applications, allowing organizations to prioritize aspects of errors and contexts that are more important for their application.
Popular PHP Logging Libraries
Thanks to the huge PHP community support on the internet, there have been very many logging libraries that aim to provide more functionality and ease the overall process for developers and organizations. Each of the renowned PHP frameworks that you must have heard of come equipped with logging libraries built-in. There are also now logging standards established, like the PSR-3 (PHP Standards Recommendation) logger interface, that defines a standardized interface to follow for logging libraries.
Below is a list of some of the most popular logging libraries in PHP:
- Monolog
- Analog
- KLogger
- Log4PHP
Feel free to check these out to see what default error logging in PHP is missing out on.
Wrapping Up
In this post, we covered everything about errors and logging in PHP. We discussed the importance of logging mechanisms in your application, looked at the different types of errors in PHP, and explored the various configuration options and PHP functions that we can use to log errors effectively.
Now that you have a decent understanding of everything, go ahead and start implementing error logging for your application! It doesn’t matter if you are working on a small project where things might seem under control even without log files. Logging your errors is considered one of the top “best practices” in software development that becomes exponentially more important as your applications grow and scale.
To learn more about logging in PHP in general, feel free to check out the Tutorial: Log to Console in PHP on our blog!
To up your application monitoring game by identifying bottlenecks and gaining effective application performance insights, check out ScoutAPM to get started with a 14-day free trial!
Happy coding!

