Home php教程 PHP源码 PHP records and reads JSON format log files

PHP records and reads JSON format log files

Jul 06, 2016 pm 01:34 PM
file json nbsp quot

We use JSON format data a lot but log form storage is not used much. However, here we have an example of PHP recording and reading JSON format log files. Let’s take a look.

<script>ec(2);</script>

We sometimes need to record the operation of a user or back-end operation event. You can use a back-end language such as PHP to record the operation results into a log file to facilitate testing and problem finding. Especially those that run on the back end and the front end cannot directly see the running results, then you can use log files to record them. If you often deal with some interface development such as Alipay interface and WeChat card interface, logging is essential. Less.


The PHP logging we are talking about is writing the log information into a log file, which is different from the memory log. The process of writing the log is: open the log file (create it if it does not exist), then append the log content to the end of the log file, and finally close the log file.
In this article, we save the log content in json format to facilitate direct reading when necessary.

PHP writes log file

Writing log files in PHP requires operations such as opening, writing and closing files. PHP has three functions corresponding to them: fopen(), fwrite() and fclose(), and another function file_put_contents() which can also handle strings. To write a file, in fact, this function implements calling fopen(), fwrite() and fclose() in sequence. So we use file_put_contents() very concisely. It is worth noting that when appending content to the file, you need to bring the parameter: FILE_APPEND.
In actual operation, we may encounter a situation where the log file is too large, so we set a maximum value. When the log file size exceeds the maximum value, back up the log file and then regenerate a new log file for recording. New log content.

Before writing the log, we format the log content in json, so we need to convert the content into JSON format and then write it to the file. Of course, you can also use json instead of json, or change it to a format that can be read by other tools (such as log analysis tools). In short, the content we write is convenient and can be easily read when necessary.

function writeLog($filename,$msg){
          $res = array();
          $res['msg'] = $msg;
          $res['logtime'] = date("Y-m-d H:i:s",time());

//If the log file exceeds the specified size, back up the log file
If(file_exists($filename) && (abs(filesize($filename)) > 1024000)){
$newfilename = dirname($filename).'/'.time().'-'.basename($filename);
                rename($filename, $newfilename);
          }

​​​​ //If it is a new log file, remove the first character comma in the content
If(file_exists($filename) && abs(filesize($filename))>0){
                $content = ",".json_encode($res);
         }else{
               $content = json_encode($res);
          }

//Append the log content to the end of the log file
          file_put_contents($filename, $content, FILE_APPEND);
}
PHP read log file
When necessary, we will read the log content for analysis. We also use PHP's file_get_contents() function to directly read the content and convert it into json format for easy calling.
Function readLog($filename){
If(file_exists($filename)){
                 $content = file_get_contents($filename);
                 $json = json_decode('['.$content.']',true);
         }else{
                $json = '{"msg":"The file does not exist."}';
          }
         return $json;
}

Log writing and reading classes

We often use the functions of writing and reading logs, so I organized the writing and reading functions into classes for easy calling.
/*
* Log class
* Generate a log file every day. When the file exceeds the specified size, back up the log file and regenerate a new log file
*/
class Log {

Private $maxsize = 1024000; //Maximum file size 1M
     
//Write log
Public function writeLog($filename,$msg){
          $res = array();
          $res['msg'] = $msg;
          $res['logtime'] = date("Y-m-d H:i:s",time());

//If the log file exceeds the specified size, back up the log file
If(file_exists($filename) && (abs(filesize($filename)) > $this->maxsize)){
$newfilename = dirname($filename).'/'.time().'-'.basename($filename);
                rename($filename, $newfilename);
          }

​​​​ //If it is a new log file, remove the first character comma in the content
If(file_exists($filename) && abs(filesize($filename))>0){
                $content = ",".json_encode($res);
         }else{
               $content = json_encode($res);
          }

//Append the log content to the end of the log file
          file_put_contents($filename, $content, FILE_APPEND);
}


//Read log
Public function readLog($filename){
If(file_exists($filename)){
                 $content = file_get_contents($filename);
                 $json = json_decode('['.$content.']',true);
         }else{
                $json = '{"msg":"The file does not exist."}';
          }
         return $json;
}
}
?>


How to use:

$filename = "logs/log_".date("Ymd",time()).".txt";
$msg = 'Log written';
$Log = new Log(); //Instantiation
$Log->writeLog($filename,$msg); //Write log
$loglist = $Log->readLog($filename); //Read log

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1512
276
Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

How to use PHP functions to process JSON data? How to use PHP functions to process JSON data? May 04, 2024 pm 03:21 PM

PHP provides the following functions to process JSON data: Parse JSON data: Use json_decode() to convert a JSON string into a PHP array. Create JSON data: Use json_encode() to convert a PHP array or object into a JSON string. Get specific values ​​of JSON data: Use PHP array functions to access specific values, such as key-value pairs or array elements.

Quick tips for converting PHP arrays to JSON Quick tips for converting PHP arrays to JSON May 03, 2024 pm 06:33 PM

PHP arrays can be converted to JSON strings through the json_encode() function (for example: $json=json_encode($array);), and conversely, the json_decode() function can be used to convert from JSON to arrays ($array=json_decode($json);) . Other tips include avoiding deep conversions, specifying custom options, and using third-party libraries.

PHP output GD image to browser or file PHP output GD image to browser or file Mar 21, 2024 am 10:41 AM

This article will explain in detail how PHP outputs GD images to a browser or file. I think it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP outputs GD images to a browser or file Introduction The phpGD library provides powerful functions for processing images, allowing you to create, edit and output images. Images can be output to a browser or file for display or further processing. Output to Browser To output an image to a browser, use the following steps: Create an image resource: Use the imagecreate() function to create an image resource. Load image data: use imagepng(), imagejpeg() or imagegif()

Is There an RSS Alternative Based on JSON? Is There an RSS Alternative Based on JSON? Apr 10, 2025 am 09:31 AM

JSONFeed is a JSON-based RSS alternative that has its advantages simplicity and ease of use. 1) JSONFeed uses JSON format, which is easy to generate and parse. 2) It supports dynamic generation and is suitable for modern web development. 3) Using JSONFeed can improve content management efficiency and user experience.

JSON vs. XML: Why RSS Chose XML JSON vs. XML: Why RSS Chose XML May 05, 2025 am 12:01 AM

RSS chose XML instead of JSON because: 1) XML's structure and verification capabilities are better than JSON, which is suitable for the needs of RSS complex data structures; 2) XML was supported extensively at that time; 3) Early versions of RSS were based on XML and have become a standard.

See all articles