- Логирование в файл PHP
- Строки текста
- Массивы
- В одну строку
- Результат работы PHP скрипта
- Запись в лог ошибок PHP
- The Ultimate Guide to PHP Log File Creation and Management
- Creating a Log File and Writing to It
- Using error_log() Function
- How to create a logfile in php php write to log file append php logger
- Leveraging Log Files for Analytics
- Laravel Logging
- Advanced Logging with Monolog and Log4PHP
- Other simple PHP code examples for writing 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); // Механизм ошибок/исключений, всегда используйте 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'); // Путь
The Ultimate Guide to PHP Log File Creation and Management
Learn how to create and manage log files in PHP with this comprehensive guide. Discover best practices, tips, and tricks for logging user behavior, detecting errors, and debugging.
- Creating a Log File and Writing to It
- Using error_log() Function
- How to create a logfile in php php write to log file append php logger
- Leveraging Log Files for Analytics
- Laravel Logging
- Advanced Logging with Monolog and Log4PHP
- Other simple PHP code examples for writing log files
- Conclusion
- How to write log file in PHP?
- How to write error log file in PHP?
- How to write console log in PHP?
- How to create an activity log in PHP?
Logging is an essential part of any application as it helps in tracking user behavior, detecting errors, and debugging. PHP provides native support for logging using log files, and in this guide, we will discuss how to create log files and write to them using PHP. We will cover the key points, important points, and helpful points related to PHP logging, including best practices, tips, and tricks.
Creating a Log File and Writing to It
To write to a log file, use the fopen() function to create a file handle. The fopen() function takes two parameters, the first one is the file name or path, and the second one is the mode in which the file will be opened. To write to a file, we need to open it in write mode, which is done by passing the ‘w’ flag.
Once we have created the file handle, we can use the fwrite() function to write to the file. The fwrite() function takes two parameters, the first one is the file handle, and the second one is the string that we want to write to the file.
fwrite($log_file, 'This is a log message.');
To create a new log file each day, use date(«j.n.Y») as part of the filename. This will create a log file with a name like logs_12.10.2021.txt .
$log_file = fopen('logs_' . date("j.n.Y") . '.txt', 'w');
Finally, use the fclose() function to close the file handle.
Using error_log() Function
The error_log() function can be used to send error messages to a given file. The first parameter of the error_log() function is the error message that we want to log, and the second parameter is the destination to which the error message will be logged.
error_log('This is an error message.', 3, 'logs.txt');
To store PHP error logs for detailed information, use custom log files instead of the default error_log file. The custom log file can be created and used in the same way as explained in the previous section.
The user should have permissions to write to the log file; otherwise, error_log will be ignored. To check the error message details, use the following code snippet.
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
The error message can be sent to a log file or a mail account using the error_log() function. To send an error message to an email account, use the following code snippet.
error_log('This is an error message.', 1, 'youremail@example.com');
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 Duration: 3:47
Leveraging Log Files for Analytics
PHP log files can be leveraged to serve as a valuable source of usage information and even basic analytics. Log messages can be generated manually by calling error_log() or automatically when notices, warnings, or errors come up during execution.
Use different log levels to categorize log messages and make it easier to filter and analyze them. PHP supports eight different log levels, as shown below.
- LOG_EMERG : System is unusable.
- LOG_ALERT : Action must be taken immediately.
- LOG_CRIT : Critical conditions.
- LOG_ERR : Error conditions.
- LOG_WARNING : Warning conditions.
- LOG_NOTICE : Normal but significant condition.
- LOG_INFO : Informational messages.
- LOG_DEBUG : Debug-level messages.
Rotate log files regularly to manage file size and avoid performance issues. Use the following code snippet to rotate log files.
$log_file = 'logs.txt'; $max_size = 1024 * 1024; // 1MB if (file_exists($log_file) && filesize($log_file) > $max_size) rename($log_file, $log_file . '.' . date('Ymd_His')); >
Laravel Logging
Laravel logging is based on “channels” where each channel represents a specific way of writing log information. Laravel provides support for writing logs to files, syslog, and even to third-party services like Slack and Papertrail.
Use the config/logging.php file to define log channels and configure logging options.
'channels' => [ 'stack' => [ 'driver' => 'stack', 'channels' => ['single'], ], 'single' => [ 'driver' => 'single', 'path' => storage_path('logs/laravel.log'), 'level' => 'debug', ], 'syslog' => [ 'driver' => 'syslog', 'level' => 'debug', ], ],
Advanced Logging with Monolog and Log4PHP
The latest advancements in php logging include using tools like Monolog and Log4PHP for advanced logging features.
Monolog provides support for different log handlers, formatters, and processors. Log4PHP is a logging framework that provides support for different appenders, layouts, and filters.
use Monolog\Logger; use Monolog\Handler\StreamHandler;$log = new Logger('name'); $log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING)); $log->warning('Foo');
use \Logger; use \LoggerLevel;$logger = Logger::getLogger('myLogger'); $logger->log(LoggerLevel::DEBUG, 'This is a debug message');
Other simple PHP code examples for writing log files
In Php , in particular, php store log in a text file
$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 , for instance, how to create a logfile in php ? code example
In Php as proof, 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
PHP logging is a powerful tool for tracking user behavior, detecting errors, and debugging. By following best practices, avoiding sensitive data logging, and rotating log files regularly, you can ensure that logging does not impact application performance and security. Use the key points, important points, and helpful points covered in this guide to create a robust logging functionality in your PHP application.