PHP.mk документација

error_log

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.error-log.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.error-log.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
error_log

Референца за `function.error-log.php` со подобрена типографија и навигација.

function.error-log.php

error_log

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

error_logИспрати порака за грешка до дефинираните рутини за обработка на грешки

= NULL

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 string.
4 message се испраќа директно до ракувачот за запишување на SAPI.
destination

Дестинацијата. Неговото значење зависи од message_type параметарот како што е опишано погоре.

additional_headers

Дополнителните заглавија. Се користи кога message_type параметар е поставен на 1. Овој тип порака ја користи истата внатрешна функција како mail() does.

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true на успех или false Враќа име на базата на податоци при успех, и message_type е нула, оваа функција секогаш враќа true, без оглед на тоа дали грешката можеше да се запише или не.

Дневник на промени

Верзија = NULL
8.0.0 destination and additional_headers се сега null.

Примери

Пример #1 error_log() examples

<?php
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
error_log("Oracle database not available!", 0);
}

// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo())) {
error_log("Big trouble, we're all out of FOOs!", 1,
"[email protected]");
}

// another way to call error_log():
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
?>

Белешки

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

error_log() не е безбедна за бинарни податоци. message ќе биде скратено со нулти карактер.

Совети

message не треба да содржи нулти карактер. Имајте предвид дека message може да се испрати до датотека, пошта, syslog, итн. Користете соодветна функција за конверзија/бегство, base64_encode(), rawurlencode() or addslashes() пред да повикате error_log().

Белешки од корисници SPL Итератори

kevindougans на gmail точка com
пред 16 години
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.
Сион
пред 7 години
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 ) );
roychri на php точка net
пред 15 години
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'.

More details here:
http://www.php.net/manual/en/errorfunc.configuration.php
frank на booksku точка com
19 години пред
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 точка buttinoni на intandtel точка com
пред 18 години
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 на kennel17 точка NOSPAM точка co точка uk
20 години пред
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.
Метју Свифт
пред 6 години
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.
russ на russtanner точка com
пред 6 години
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".
SJL
пред 18 години
"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.
Анонимен
пред 22 години
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, "[email protected]", 
  "Subject: Foo\nFrom: [email protected]\n");

?>

---------------%<-----------------------
To: [email protected]
Envelope-to: [email protected]
Date: Fri, 28 Mar 2003 13:29:02 -0500
From: [email protected]
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
p точка lhonorey на nospam-laposte точка net
19 години пред
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,"[email protected]","subject  :lunch\nContent-Type: text/html; charset=ISO-8859-1");

Enjoy !
franz на fholzinger точка com
20 години пред
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
paul точка chubb на abs точка gov точка au
пред 17 години
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); 
}
stepheneliotdewey на GmailDotCom
пред 18 години
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.
eguvenc на gmail точка com
пред 17 години
<?php
//Multiline error log class
// ersin güvenç 2008 [email protected]
//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
?>
daniel точка fukuda на gmail точка com
пред 16 години
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.
Роберт Чапин
пред 7 години
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'); ?>
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.