error log что это

(PHP 4, PHP 5, PHP 7)

error_log — Отправляет сообщение об ошибке заданному обработчику ошибок

Описание

Отправляет сообщение об ошибке в лог web-сервера или в пользовательский файл.

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

Сообщение об ошибке которое должно быть логировано.

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

error_log() log types

0 Сообщение message отправляется в системный регистратор PHP, используя механизм логирования операционной системы, или файл, в зависимости от значения директивы error_log в конфигурационном файле. Это значение по умолчанию.
1 Сообщение message отправляется электронной почтой на адрес, установленный в параметре destination . Это единственный тип сообщения, где используется четвертый параметр extra_headers .
2 Больше не используется.
3 message применяется к указанному в destination файлу. Перенос строки автоматически не добавляется в конец message .
4 Сообщение message отправляется напрямую в обработчик логера SAPI.

Назначение. Устанавливается в зависимости от параметра 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()

// Отправляет уведомление посредством серверного лога, если мы не можем
// подключиться к базе данных.
if (! Ora_Logon ( $username , $password )) <
error_log ( «Oracle database not available!» , 0 );
>

Большой англо-русский и русско-английский словарь . 2001 .

Смотреть что такое «error log» в других словарях:

error.log — (в UNIX подобных системах error log[1]) журнальный файл, используемый веб сервером для журналирования возникших на сервере ошибок, позволяющий определить тип ошибки, а также причину её возникновения. Представляет собой текстовый файл, каждая… … Википедия

Log analysis — (or system and network log analysis ) is an art and science seeking to make sense out of computer generated records (also called log or audit trail records). The process of creating such records is called data logging.Typical reasons why people… … Wikipedia

log file — ➔ file1 * * * log file UK US noun [C] IT ► a computer file that contains a record of all actions that have been done on a computer, a website, etc.: »Many online news organizations log files show that photo galleries are among their most popular… … Financial and business terms

log — <>I.<> noun 1 wood ADJECTIVE ▪ cut, sawn ▪ a pile of sawn logs ▪ fallen ▪ The road was blocked by fallen logs. ▪ … Collocations dictionary

Log-normal distribution — Probability distribution name =Log normal type =density pdf μ=0 cdf μ=0 parameters =sigma > 0 infty Wikipedia

Server log — A server log is a log file (or several files) automatically created and maintained by a server of activity performed by it. A typical example is a web server log which maintains a history of page requests. The W3C maintains a standard format (the … Wikipedia

Access.log — файл, использующийся веб серверами (Apache, nginx, lighthttpd, boa, прокси сервером squ >Википедия

access.log — access.log файл, использующийся веб серверами (Apache, Nginx, Lighttpd, boa, прокси сервером squ >Википедия

SCSI log pages — SCSI target devices prov >Wikipedia

Standard error (statistics) — For a value that is sampled with an unbiased normally distributed error, the above depicts the proportion of samples that would fall between 0, 1, 2, and 3 standard deviations above and below the actual value. The standard error is the standard… … Wikipedia

(PHP 4, PHP 5, PHP 7)

error_log — Отправляет сообщение об ошибке заданному обработчику ошибок

Описание

Отправляет сообщение об ошибке в лог веб-сервера или в пользовательский файл.

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

Сообщение об ошибке, которое должно быть логировано.

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

Типы журналов error_log()

0 Сообщение message отправляется в системный регистратор PHP, используя механизм логирования операционной системы, или файл, в зависимости от значения директивы error_log в конфигурационном файле. Это значение по умолчанию.
1 Сообщение message отправляется электронной почтой на адрес, установленный в параметре destination . Это единственный тип сообщения, где используется четвертый параметр extra_headers .
2 Больше не используется.
3 message применяется к указанному в destination файлу. Перенос строки автоматически не добавляется в конец message .
4 Сообщение message отправляется напрямую в обработчик логера SAPI.

Назначение. Устанавливается в зависимости от параметра 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()

// Отправляет уведомление посредством серверного лога, если мы не можем
// подключиться к базе данных.
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» );
?>

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

Версия Описание
5.2.7 Добавлен 4-й тип значения в message_type .

User Contributed Notes 18 notes

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.

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!

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» ,
«Subject: Foo
From: Rizzlas@my.domain
» );

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.

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);
>

«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.

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.

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
Content-Type: text/html; charset=ISO-8859-1″);

//Multiline error log class
// ersin güvenç 2008 eguvenc@gmail.com
//For break use »
» instead ‘

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 . »
» ;
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 . »
» ;
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
?>

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:

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