Php print to file log

How to print a debug log?

I’d like to debug some PHP code, but I guess printing a log to screen or file is fine for me. How should I print a log in PHP code? The usual print / printf seems to go to HTML output not the console. I have Apache server executing the PHP code.

Is your script running in a web browser or in a console (aka parsed using php.exe rather than apache/iis)?

You should look at this question, has a bit of useful logging code: stackoverflow.com/questions/5769537/…

15 Answers 15

A lesser known trick is that mod_php maps stderr to the Apache log. And, there is a stream for that, so file_put_contents(‘php://stderr’, print_r($foo, TRUE)) will nicely dump the value of $foo into the Apache error log.

+ oned for mentionning that, btw you can also set the value of error_log to ‘php://stdout’ when debugging a console app and have the error messages appear straight to console, ie: error_log(«You messed up!», 3, «php://stdout»);

+1 It took me too long to find this answer. This is all I really was looking for. I couldn’t figure out how to see what my array contained (working in Drupal).

I would also suggest using var_export($foo, true) instead of print_r($foo, true) if print_r doesn’t get you the type information you need.

error_log(print_r($variable, TRUE)); 

Unfortunately, this is the most convenient solution. Xdebug is to heavy to run it all the time. Voted for you

Читайте также:  Apache poi java api

You can use error_log to send to your servers error log file (or an optional other file if you’d like)

file_put_contents('your_log_file', 'your_content'); 
error_log ('your_content', 3, 'your_log_file'); 

This will show continuously the last line put in the file.

One may also append to a log file using file_put_contents(‘your_log_file’, ‘your_content’, FILE_APPEND) .

You need to change your frame of mind. You are writing PHP, not whatever else it is that you are used to write. Debugging in PHP is not done in a console environment.

In PHP, you have 3 categories of debugging solutions:

  1. Output to a webpage (see dBug library for a nicer view of things).
  2. Write to a log file
  3. In session debugging with xDebug

Learn to use those instead of trying to make PHP behave like whatever other language you are used to.

As one who spends a lot of time writing console apps and various non web scripts, I will politely disagree with that.

I do work a lot maintaining and developping console applications and in my bad english interpretation of the question had assumed he was looking to debug a console app. Xdebug is fine and very handy though I do like debugging info right in my editor

@Stefgosselin: Netbeans does pretty much the same, although the best I have seen with xDebug was with Aptana.

I use xDebug on Netbeans and it works fine most of the time. But, there are times when you need to log stuff on a file.

Are you debugging on console? There are various options for debugging PHP. The most common function used for quick & dirty debugging is var_dump.

That being said and out of the way, although var_dump is awesome and a lot of people do everything with just that, there are other tools and techniques that can spice it up a bit.

Things to help out if debugging in a webpage, wrap tags around your dump statement to give you proper formatting on arrays and objects.

And, last but not least make sure if debugging your error handling is set to display errors. Adding this at the top of your script may be needed if you cannot access server configuration to do so.

error_reporting(E_ALL); ini_set('display_errors', '1'); 

You can also write to a file like this:

$logFilePath = '../logs/debug.text'; ob_start(); // if you want to concatenate: if (file_exists($logFilePath)) < include($logFilePath); >// for timestamp $currentTime = date(DATE_RSS); // echo log statement(s) here echo "\n\n$currentTime - [log statement here]"; $logFile = fopen($logFilePath, 'w'); fwrite($logFile, ob_get_contents()); fclose($logFile); ob_end_flush(); 

Make sure the proper permissions are set so php can access and write to the file ( 775 ).

If you don’t want to integrate a framework like Zend, then you can use the trigger_error method to log to the php error log.

Simply way is trigger_error:

but you can’t put arrays or Objects therefore use

trigger_error is probably the best way to write to your error logs. You will thank yourself when you want to modify say the log lines with some custom data later.

You can use the php curl module to make calls to http://liveoutput.com/. This works great in an secure, corporate environment where certain restrictions in the php.ini exists that restrict usage of file_put_contents .

This a great tool for debugging & logging php: PHp Debugger & Logger

It works right out of the box with just 3 lines of code. It can send messages to the js console for ajax debugging and can replace the error handler. It also dumps information about variables like var_dump() and print_r(), but in a more readable format. Very nice tool!

I have used many of these, but since I usually need to debug when developing, and since I develop on localhost, I have followed the advice of others and now write to the browser’s JavaScript debug console (see http://www.codeforest.net/debugging-php-in-browsers-javascript-console).

That means that I can look at the web page which my PHP is generating in my browser & press F12 to quickly show/hide any debug trace.

Since I am constantly looking at the developer tools for debugger, CSS layout, etc, it makes sense to look at my PHP loggon there.

If anyone does decide to us that code, I made one minor change. After

function debug($name, $var = null, $type = LOG)

This is because my server side PHP generates HTML conatining JavaScript & I find it useful to distinguish between output from PHP & JS.

(Note: I am currently updating this to allow me to switch on & off different output types: from PHP, from JS, and database access)

Источник

Запись в лог-файл в 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'); // Путь

Источник

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