- Запись в лог-файл в PHP
- Строки текста
- Запись в лог-файле:
- Массивы
- Запись в лог-файле:
- В одну строку
- Результат работы PHP скрипта
- Запись в лог-файле:
- Запись в лог ошибок PHP
- Effective PHP Logging: Best Practices for Writing and Appending to Log Files
- Using file_put_contents() to append to a log file
- Using fopen() and fwrite() to append to a log file
- How to create a logfile in php php write to log file append php logger
- Enabling error logging in PHP
- Using error_log() to send error messages to a log file
- Best practices for logging in PHP
- Other PHP code examples for writing to and appending to log files
- Conclusion
Запись в лог-файл в 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] Запись в лог
Effective PHP Logging: Best Practices for Writing and Appending to Log Files
Learn how to write and append log files in PHP using file_put_contents(), fopen(), and fwrite(). Follow best practices for logging, including error logging and using a logging framework. Optimize your software development process with effective PHP logging. Get started now!
As a developer, ensuring your application is free of errors and bugs is crucial. One essential aspect of software development is logging, which helps you track errors and debug issues in your code. In PHP, logging can be achieved by creating and appending to log files in different ways. In this post, I will cover the best practices for writing and appending to log files in PHP, including helpful tips and tricks for effective logging.
Using file_put_contents() to append to a log file
The file_put_contents() function provides a simple way to create or append to a text file in PHP. To append data to a file using this function, you can use the FILE_APPEND and LOCK_EX arguments. Here is an example code snippet:
file_put_contents('log.txt', $logMessage, FILE_APPEND | LOCK_EX);
In this code snippet, log.txt refers to the name of the log file, $logMessage is the message to be logged, and FILE_APPEND | LOCK_EX is used to append data to the file while ensuring file locking.
Using fopen() and fwrite() to append to a log file
Another way to create or append to a log file in PHP is by using the fopen() and fwrite() functions. The fopen() function can be used to open a file in different modes, including “a” or “a+” for appending data to a file. The fwrite() function, on the other hand, can be used to write data to a file, including appending data to the end of a file. Here is an example code snippet:
$file = fopen('log.txt', 'a'); fwrite($file, $logMessage); fclose($file);
In this code snippet, log.txt refers to the name of the log file, $logMessage is the message to be logged, and fclose() is used to close the file after writing.
How to create a logfile in php php write to log file append php logger
how to create a logfile in php | php write to log file append | php loggerphp fwrite append,php Duration: 3:47
Enabling error logging in PHP
Enabling error logging in PHP allows you to log errors and exceptions that occur in your application. You can use the ini_set() command to enable error logging in PHP and specify the location of the error log file . Here is an example code snippet:
ini_set('error_log', '/var/log/php-errors.log');
In this code snippet, /var/log/php-errors.log refers to the location where the error log file will be stored.
Using error_log() to send error messages to a log file
The error_log() function can be used to send error messages to a system logger or file. It offers more customization options than ini_set() . Here is an example code snippet:
error_log('Error message', 3, '/var/log/php-errors.log');
In this code snippet, «Error message» is the message to be logged, 3 refers to the message type (which is ERROR ), and /var/log/php-errors.log is the location where the error log file will be stored.
Best practices for logging in PHP
To effectively log messages in PHP, there are best practices that should be followed. These include:
- Use meaningful and consistent log messages to make debugging easier. Avoid using generic messages like “Error occurred” or “Warning”.
- Set appropriate log levels to control the amount of information logged. For instance, use INFO for general information, WARN for warnings, and ERROR for errors.
- Avoid logging sensitive information such as passwords or credit card numbers. This is to prevent unauthorized access to such information.
- Use a logging framework or library to simplify the process of logging and offer additional features and benefits such as log rotation and filtering.
Other PHP code examples for writing to and appending to log files
In Php as proof, appending txt file from php code sample
$log_content="This line is logged on 2020-08-14 09:55:00"; $myfile = fopen("log.txt", "a") or die("Unable to open file!"); fwrite($myfile, $log_content); fclose($myfile);
In Php , log data into file php code example
//Something to write to txt log $log = "User: ".$_SERVER['REMOTE_ADDR'].' - '.date("F j, Y, g:i a").PHP_EOL. "Attempt: ".($result[0]['success']=='1'?'Success':'Failed').PHP_EOL. "User: ".$username.PHP_EOL. "-------------------------".PHP_EOL; //Save string to log, use FILE_APPEND to append. file_put_contents('./log_'.date("j.n.Y").'.log', $log, FILE_APPEND);
Conclusion
Logging is a crucial aspect of software development that helps developers track errors and debug issues in their code. In PHP, there are several ways to accomplish this, including file_put_contents() , fopen() , and fwrite() . Enabling error logging and using best practices for logging can help developers track errors and debug issues in their code more effectively. By following these tips and tricks, developers can create more reliable and robust applications that are easier to maintain and troubleshoot.