Php log data to file

Логирование в файл 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'); // Путь

Источник

Читайте также:  Css after width 100

Logging to a file with PHP.

This is a guide on how to log to a file using PHP. Custom PHP logging can be extremely useful if you are trying to debug an issue or collect statistics. In the past, I have resolved a number of issues by simply logging information to a file and then reviewing it.

Do not underestimate the importance of logging!

Logging to a file with PHP.

In PHP, you can use the file_put_contents function to write data to a file. Take a look at the following code example:

An explanation of the PHP code above:

  1. We created an array containing the information that we want to log. In the case above, I am wanting to log the date and time, the user’s IP address and two other pieces of custom information. I store these in an array because I personally find the code easier to read. It also means that I can easily add more data to the log without worrying about delimiters, etc.
  2. We used PHP’s implode function to convert the array data into a single line of text. In the code above, I used the hyphen character as a delimiter. You can obviously change this to meet your own needs. Note that the delimiter should not be found in the rest of your data, as the purpose of a delimiter is to specify the boundary between separate pieces of plain text. Essentially, it allows us to split the log file up into its relevant parts.
  3. We added a newline onto the end of the text. This is important as it makes the log file easier to read. I used the PHP_EOL constant instead of manually typing out a newline because the PHP_EOL constant helps to prevent cross-platform issues.
  4. We created the name of our log file. In the case above, the log file will exist in the same directory of the PHP script that created it. You can also specify a full path to the log file if needs me. Personally, I would suggest that you modify this and supply a full path to the log file you want to create.
  5. Finally, we logged the data to our file using file_put_contents. Note how we used the FILE_APPEND flag as the third parameter. This is extremely important, as it tells the file_put_contents function to log our data at the end of the file. Without it, PHP would overwrite any existing data.

After running the code above, the following text was written to my log:

2018-11-15 08:20:16 - 127.0.0.1 - Clicked on item 4 - Number of items in cart is 2

Источник

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