Write log files in php

How to write to error log file in PHP [closed]

I want to write a message to an error log file when executing PHP code. I am trying to use the PHP error_log() function Docs. But it’s not working properly for me.

Please show your code, tell what you expected to happen, describe what happens instead. Normally the error_log() function just works and you have not said what exactly did not work for you so your question is not clear.

This could stem from a permissions issue where the user you created the error log file for is different than the user being used by Apache to write to the file. Check out ‘/etc/apache2/envvars/’ file for a possible fix.

4 Answers 4

If you don’t want to change anything in your php.ini file, according to PHP documentation, you can do this.

error_log("Error message\n", 3, "/mypath/php.log"); 

The first parameter is the string to be sent to the log. The second parameter 3 means expect a file destination. The third parameter is the log file path.

I’m just doing error_log(«Error message\n») but nothing appears in /var/log/httpd/error_log . 🙁 Any idea why?

In php.ini file check the error_log configuration setting. This setting will hold the file name that errors are written to. e.g. error_log «log_file_name» . More details at php.net/manual/en/function.error-log.php

Читайте также:  Python pandas groupby level

@suspectus, your answer is what I had been looking for long enough. I believe the third parameter could be any file that I like to log the Error message\n to. Am I correct?

By default, the message will be send to the php system logger.

If you use this method, be sure that error logging is turned on and that you uncomment the error_log directive in php.ini.

-1 for suggesting, a year after the question was asked, what the OP already said he tried, but did not work for him. Also, there is already a BETTER answer by suspectus, created a year before this answer.

@ToolmakerSteve He didn’t actually say how he was using it, just that he was trying to use it. The accepted (and very good) answer uses error_log too.

We all know that PHP save errors in php_errors.log file.

But, that file contains a lot of data.

If we want to log our application data, we need to save it to a custom location.

We can use two parameters in the error_log function to achieve this.

error_log(print_r($v, TRUE), 3, '/var/tmp/errors.log'); 

print_r($v, TRUE) : logs $v (array/string/object) to log file. 3 : Put log message to custom log file specified in the third parameter.

‘/var/tmp/errors.log’ : Custom log file (This path is for Linux, we can specify other depending upon OS).

OR, you can use file_put_contents()

file_put_contents('/var/tmp/e.log', print_r($v, true), FILE_APPEND); 

‘/var/tmp/errors.log’: Custom log file (This path is for Linux, we can specify other depending upon OS). print_r($v, TRUE) : logs $v (array/string/object) to log file. FILE_APPEND: Constant parameter specifying whether to append to the file if it exists, if file does not exist, new file will be created.

Источник

Запись в лог-файл в PHP

Несколько вариантов как быстро организовать запись данных в лог-файл.

Строки текста

$log = date('Y-m-d H:i:s') . ' Запись в лог'; file_put_contents(__DIR__ . '/log.txt', $log . PHP_EOL, FILE_APPEND);

Запись в лог-файле:

2019-02-02 16:00:38 Запись в лог

Массивы

Если нужно записать в лог обычный массив, массив с индексами или многомерный массив, поможет функция 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);

Запись в лог-файле:

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);
2019-02-02 16:56:00 Array([foo] => bar[helo] => world[array] => Array([0] => 1[1] => 2))

Результат работы PHP скрипта

Если нужно добавить в лог результат работы PHP скрипта, помогут функции буферизации ob_start() и ob_get_clean() .

ob_start(); // Вывод заголовков браузера. foreach (getallheaders() as $name => $value) < echo "$name: $value\n"; >$log = date('Y-m-d H:i:s') . PHP_EOL . ob_get_clean() . PHP_EOL; file_put_contents(__DIR__ . '/log.txt', $log, FILE_APPEND);

Запись в лог-файле:

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

Запись в лог ошибок PHP

Если логирование предполагает фиксацию только ошибок, то лучше писать их в общий лог PHP, подробнее на php.net.

error_reporting(E_ALL); ini_set('error_log', __DIR__ . '/php-errors.log'); error_log('Запись в лог', 0);
[02-Feb-2019 20:18:17 Europe/Moscow] Запись в лог

Источник

Логирование в файл PHP

На этой странице представленно несколько вариантов как быстро организовать запись данных в лог-файл.

Строки текста

$log = date('Y-m-d H:i:s') . ' Запись в лог'; file_put_contents(__DIR__ . '/log.txt', $log . PHP_EOL, FILE_APPEND);
2019-02-02 16:00:38 Запись в лог

Массивы

Если нужно записать в лог обычный массив, массив с индексами или многомерный массив, поможет функция 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);
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);
2019-02-02 16:56:00 Array([foo] => bar[helo] => world[array] => Array([0] => 1[1] => 2))

Результат работы PHP скрипта

Если нужно добавить в лог результат работы PHP скрипта, помогут функции буферизации ob_start() и ob_get_clean() .

ob_start(); // Вывод заголовков браузера. foreach (getallheaders() as $name => $value) < echo "$name: $value\n"; >$log = date('Y-m-d H:i:s') . PHP_EOL . ob_get_clean() . PHP_EOL; file_put_contents(__DIR__ . '/log.txt', $log, FILE_APPEND);
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

Запись в лог ошибок PHP

Если логирование предполагает фиксацию только ошибок, то лучше писать их в общий лог PHP, подробнее на php.net.

error_reporting(E_ALL); // Механизм ошибок/исключений, всегда используйте E_ALL ini_set('ignore_repeated_errors', TRUE); // Всегда используйте TRUE ini_set('display_errors', FALSE); // Отображение ошибки/исключения, используйте значение FALSE только в рабочей среде или на реальном сервере, используйте TRUE в среде разработки ini_set('log_errors', TRUE); // Механизм протоколирования файлов ошибок/исключений ini_set('error_log', 'errors.log'); // Путь

Источник

How do I log errors and warnings into a file?

How do I turn on all error and warnings and log them to a file, but to set up all of that within the script (not changing anything in php.ini)? I want to define a file name and so that all errors and warnings get logged into it.

9 Answers 9

ini_set("log_errors", 1); ini_set("error_log", "/tmp/php-error.log"); error_log( "Hello, errors!" ); 

Or update php.ini as described in this blog entry from 2008.

ini_set does only work if that code is executed. Not useful for code that has parse errors because the error will be before the code is executed. Instead write those changes into the php.ini.

If you can’t edit php.ini, you should be able to add this in the .htaccess : php_flag log_errors on php_value error_log /home/path/public_html/domain/PHP_errors.log . See perishablepress.com/…

error_log("You messed up!", 3, "/var/tmp/my-errors.log"); 

You can customize error handling with your own error handlers to call this function for you whenever an error or warning or whatever you need to log occurs. For additional information, please refer to the Chapter Error Handling in the PHP Manual

Simply put these codes at top of your PHP/index file:

error_reporting(E_ALL); // Error/Exception engine, always use E_ALL ini_set('ignore_repeated_errors', TRUE); // always use TRUE ini_set('display_errors', FALSE); // Error/Exception display, use FALSE only in production environment or real server. Use TRUE in development environment ini_set('log_errors', TRUE); // Error/Exception file logging engine. ini_set('error_log', 'your/path/to/errors.log'); // Logging file path 

That’s only if you also want all errors to be displayed in output and/or to the browser, in addition to logging. display_errors should NEVER be turned on on a live production server — that directive is specifically for output to the user, and has no effect on logging. php.net/manual/en/…

Add this code in file .htaccess (as an alternative to file php.ini or the ini_set function):

 php_flag log_errors on php_value error_log ./path_to_MY_PHP_ERRORS.log # php_flag display_errors on 
  • as commented: this is for Apache-type servers, and not for Nginx or others.

That’s my personal short function

# logging /* [2017-03-20 3:35:43] [INFO] [file.php] Here we are [2017-03-20 3:35:43] [ERROR] [file.php] Not good [2017-03-20 3:35:43] [DEBUG] [file.php] Regex empty mylog ('hallo') -> INFO mylog ('fail', 'e') -> ERROR mylog ('next', 'd') -> DEBUG mylog ('next', 'd', 'debug.log') -> DEBUG file debug.log */ function mylog($text, $level='i', $file='logs') < switch (strtolower($level)) < case 'e': case 'error': $level='ERROR'; break; case 'i': case 'info': $level='INFO'; break; case 'd': case 'debug': $level='DEBUG'; break; default: $level='INFO'; >error_log(date("[Y-m-d H:i:s]")."\t[".$level."]\t[".basename(__FILE__)."]\t".$text."\n", 3, $file); > 

An explanation would be in order. E.g., what is the idea/gist? Please respond by editing (changing) your answer, not here in comments (without «Edit:», «Update:», or similar — the answer should appear as if it was written today).

Take a look at the log_errors configuration option in php.ini. It seems to do just what you want to. I think you can use the error_log option to set your own logging file too.

When the log_errors directive is set to On , any errors reported by PHP would be logged to the server log or the file specified with error_log . You can set these options with ini_set too, if you need to.

(Please note that display_errors should be disabled in php.ini if this option is enabled)

Why should display_errors be disabled if you enable log_errors ? Doesn’t make sense in my opinion. 🙂

Because there’s no need to output the content of the errors to the public on a production server, especially if the text of the error is being discreetly logged into a file.

Display errors should be always disabled on production server. Not if error logging is configured to somewhere else, but always. Errors are logged to apache error log by default, that is often enough.

None of these answers mention the importance or relevance to Agile teams; professional-level development work is more often than not done within the context of a squad.

Keeping in mind that many development teams use a task-tracking tool such as JIRA , I prefer to use a timestamp to log each error as a separate file:

error_reporting(E_ALL); ini_set('log_errors', 1); ini_set('error_log', $_SERVER['DOCUMENT_ROOT'] . '/logs/php/php-errors-' . time() . '.txt'); 

Using this approach, it is easy for a Project Manager or Team Lead to then isolate each error as a specific file that can then be attached to a unique JIRA defect, assigned to a developer, and tracked (the timestamp can be linked within the defect to easily track while the defect fix is In-Progress). When the issue is closed, then the file can be deleted from the log directory, while a copy of it (if needed for future reference) can be accessed in the JIRA.

Источник

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