Php script log to file

Write to a log file with PHP

After writing custom PHP “log” function several times I finally decided to create a simple Logging PHP class. First call of lwrite method will open log file implicitly and write line to the file. Every other lwrite will use already opened file pointer until closing file with lclose. It is always a good idea to close file when it’s done. This should prevent file from corruption and overhead in closing file is negligible.

Before you read further, I also wrote a post how to Log PHP errors to the separate file, if you are looking for such information.

// Logging class initialization $log = new Logging(); // set path and name of log file (optional) $log->lfile('/tmp/mylog.txt'); // write message to the log file $log->lwrite('Test message1'); $log->lwrite('Test message2'); $log->lwrite('Test message3'); // close log file $log->lclose();

Output in mylog.txt will look like:

[10/Jun/2012:10:36:19] (test) Test message1 [10/Jun/2012:10:36:19] (test) Test message2 [10/Jun/2012:10:36:19] (test) Test message3

Logging class source code:

/** * Logging class: * - contains lfile, lwrite and lclose public methods * - lfile sets path and name of log file * - lwrite writes message to the log file (and implicitly opens log file) * - lclose closes log file * - first call of lwrite method will open log file implicitly * - message is written with the following format: [d/M/Y:H:i:s] (script name) message */ class Logging < // declare log file and file pointer as private properties private $log_file, $fp; // set log file (path and name) public function lfile($path) < $this->log_file = $path; > // write message to the log file public function lwrite($message) < // if file pointer doesn't exist, then open log file if (!is_resource($this->fp)) < $this->lopen(); > // define script name $script_name = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME); // define current time and suppress E_WARNING if using the system TZ settings // (don't forget to set the INI setting date.timezone) $time = @date('[d/M/Y:H:i:s]'); // write current time, script name and message to the log file fwrite($this->fp, "$time ($script_name) $message" . PHP_EOL); > // close log file (it's always a good idea to close a file when you're done with it) public function lclose() < fclose($this->fp); > // open log file (private method) private function lopen() < // in case of Windows set default log file if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') < $log_file_default = 'c:/php/logfile.txt'; >// set default log file for Linux and other systems else < $log_file_default = '/tmp/logfile.txt'; >// define log file from lfile method or use previously set default $lfile = $this->log_file ? $this->log_file : $log_file_default; // open log file for writing only and place file pointer at the end of the file // (if the file does not exist, try to create it) $this->fp = fopen($lfile, 'a') or exit("Can't open $lfile!"); > >

For PHP prior to version 5.2.0 you will have to replace or change line with built-in PHP function pathinfo() because PATHINFO_FILENAME constant was added in PHP 5.2.0

// for PHP 5.2.0+ $script_name = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME); // for PHP before version 5.2.0 $script_name = basename($_SERVER['PHP_SELF']); $script_name = substr($script_name, 0, -4); // php extension and dot are not needed

If you want to send a message to the PHP’s system logger, please see the error_log PHP command.

Читайте также:  Get sql exception in java

Источник

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

Источник

Читайте также:  Python qt button connect

Php script log to file

  • Different ways to write a PHP code
  • How to write comments in PHP ?
  • Introduction to Codeignitor (PHP)
  • How to echo HTML in PHP ?
  • Error handling in PHP
  • How to show All Errors in PHP ?
  • How to Start and Stop a Timer in PHP ?
  • How to create default function parameter in PHP?
  • How to check if mod_rewrite is enabled in PHP ?
  • Web Scraping in PHP Using Simple HTML DOM Parser
  • How to pass form variables from one page to other page in PHP ?
  • How to display logged in user information in PHP ?
  • How to find out where a function is defined using PHP ?
  • How to Get $_POST from multiple check-boxes ?
  • How to Secure hash and salt for PHP passwords ?
  • Program to Insert new item in array on any position in PHP
  • PHP append one array to another
  • How to delete an Element From an Array in PHP ?
  • How to print all the values of an array in PHP ?
  • How to perform Array Delete by Value Not Key in PHP ?
  • Removing Array Element and Re-Indexing in PHP
  • How to count all array elements in PHP ?
  • How to insert an item at the beginning of an array in PHP ?
  • PHP Check if two arrays contain same elements
  • Merge two arrays keeping original keys in PHP
  • PHP program to find the maximum and the minimum in array
  • How to check a key exists in an array in PHP ?
  • PHP | Second most frequent element in an array
  • Sort array of objects by object fields in PHP
  • PHP | Sort array of strings in natural and standard orders
  • How to pass PHP Variables by reference ?
  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?
  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to get the time of the last modification of the current page in PHP?
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?
  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to create a string by joining the array elements using PHP ?
  • How to prepend a string in PHP ?
Читайте также:  Mat to image java

Источник

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