- Php error log windows
- Описание
- error_log — Отправляет сообщение об ошибке заданному обработчику ошибок
- Описание
- Список параметров
- Возвращаемые значения
- Примечания
- Примеры
- Формат файла журнала ошибок PHP (директива php.ini error_log) в Windows
- error_log
- Описание
- Список параметров
- Возвращаемые значения
- Примечания
- Примеры
- User Contributed Notes 20 notes
- stuff
Php error log windows
(PHP 3, PHP 4, PHP 5)
error_log — высылает сообщение об ошибке.
Описание
int error_log ( string message [, int message_type [, string destination [, string extra_headers]]])
Высылает сообщение об ошибке в error log web-сервера, TCP -порт или в файл. Первый параметр message это сообщение об ошибке, которое должно быть записано в лог-файл. Второй параметр, message_type , говорит, куда сообщение должно быть направлено:
Таблица 1. Типы error_log()
0 | message высылается в системный логер РНР, используя механизм логинга ОС, или в файл, в зависимости от установки директивы конфигурации error_log. |
1 | message высылается по email по адресу в параметре destination . Это единственный тип сообщения с 4 параметром, extra_headers . Этот тип сообщений использует ту же внутреннюю функцию, что и mail() . |
2 | message высылается через соединение отладки РНР. Эта опция доступна, только если включена опция удалённой отладки. В этом случае параметр destination специфицирует имя хоста или IP-адрес, или — по выбору — номер порта сокета, получающего отладочную информацию. |
3 | message присоединяется к файлу destination . |
Предупреждение! | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Удалённая отладка по TCP/IP это возможность PHP 3, которая недоступна в PHP 4. error_log — Отправляет сообщение об ошибке заданному обработчику ошибок(PHP 4, PHP 5, PHP 7) error_log — Отправляет сообщение об ошибке заданному обработчику ошибок ОписаниеОтправляет сообщение об ошибке в лог web-сервера или в пользовательский файл. Список параметровСообщение об ошибке которое должно быть логировано. Определяет куда отправлять ошибку. Возможны следующие значения:
Назначение. Устанавливается в зависимости от параметра message_type . Дополнительные заголовки. Используется, когда значение параметра message_type — 1. Данный тип сообщения использует ту же внутреннюю функцию, что и mail() . Возвращаемые значенияВозвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки. Примечанияerror_log() не является бинарнобезопасным. message обрезается по null-символу. message не должен содержать null-символ. Учтите, что message может передаваться в файл, по почте, в syslog, и т.д.. Используйте подходящую преобразующую или экранирующую функцию, base64_encode() , rawurlencode() или addslashes() перед вызовом error_log() . ПримерыПример #1 Примеры использования error_log() // Отправляет уведомление посредством серверного лога, если мы не можем Формат файла журнала ошибок PHP (директива php.ini error_log) в WindowsНапример: Файл журнала ошибок (c: /php/php.log) содержит каждую запись в этом формате: Два символа возврата каретки и одна новая строка на одну строку ошибок. Почему так происходит? Как изменить файл журнала ошибок на формат по умолчанию: Версия PHP 5.3.6 Файл php.ini содержит только две строки скрипт apache phpinfo () -> http://pastehtml.com/view/awvx1vgpp.html sever: nginx 1.0.4 Все работает так, как ожидалось. Существует больше директив ini для управления выходом в журнале ошибок. Если это не непонимание конца строки (см. Мой комментарий), то вы можете захотеть посмотреть в ini-настройках error_prepend_string и error_append_string . Эти две и более связанные настройки описаны на этой странице руководства PHP . По умолчанию PHP работает, не загружая ini и только включив установку и регистрацию error_log , он выводит только одну строку. Вы можете проверить это и на своей системе: Используйте эту команду, чтобы сделать изолированный прогон и сравнить его с вашим выходом. Если он имеет два конца строки, то это, вероятно, ошибка вашей версии php. Если нет, то в вашем приложении некоторые параметры будут изменены. Вам нужно выяснить, какая настройка. Вероятно, вы можете найти его, зарегистрировав собственный обработчик ошибок и затем наложив настройки ini. error_log(PHP 4, PHP 5, PHP 7, PHP 8) error_log — Отправляет сообщение об ошибке заданному обработчику ошибок ОписаниеОтправляет сообщение об ошибке в лог веб-сервера или в пользовательский файл. Список параметровСообщение об ошибке, которое должно быть логировано. Определяет куда отправлять ошибку. Возможны следующие значения:
Назначение. Устанавливается в зависимости от параметра message_type . Дополнительные заголовки. Используется, когда значение параметра message_type — 1 . Данный тип сообщения использует ту же внутреннюю функцию, что и mail() . Возвращаемые значенияВозвращает true в случае успешного завершения или false в случае возникновения ошибки. Если message_type равен нулю, функция всегда возвращает true , независимо от того, может ли ошибка логироваться или нет. Примечанияerror_log() не является бинарно-безопасной функцией. message обрезается по null-символу. message не должен содержать null-символ. Учтите, что message может передаваться в файл, по почте, в syslog и т.д. Используйте подходящую преобразующую или экранирующую функцию, base64_encode() , rawurlencode() или addslashes() перед вызовом error_log() . ПримерыПример #1 Примеры использования error_log() // Отправляет уведомление посредством серверного лога, если мы не можем // Уведомить администратора по электронной почте, если невозможно выделить ресурсы для FOO // другой способ вызвать error_log(): User Contributed Notes 20 notesAdvice 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. 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, There is a limit on the maximum length that you can pass as the $message. The default seem to be 1024 but can be changed by adjusting the value of the runtime configuration value of ‘log_errors_max_len’. 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! 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. 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»: 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». 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. ( «sometext» , 1 , «zigzag@my.domain» , 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) < «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. 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. 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. stuff«,1,»eat@joe.com»,»subject :lunch\nContent-Type: text/html; charset=ISO-8859-1″); 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.’; //Multiline error log class Class log < /* $log = new log (); 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: After scouring the internet for getting event logging to |