» » Record and read JSON format log files by PHP

 

Record and read JSON format log files by PHP

Author: bamboo06 on 11-11-2017, 17:34, views: 6559

1
Sometimes we need to record the operation of an operation event of the user or back-end, you can use the back-end language such as PHP to log the operation results to the log file, easy to test and find the problem. In particular, these are running in the back-end and the front can not directly see the results of the operation, then you can use the log file to record, if you often interface with some interfaces such as paypal interface, amazon card interface, log records will be not enough.
Record and read JSON format log files by PHP

We talk about PHP log records, log information is written to a log file, different from the memory log. The process of writing to the log is to open the log file (newly created if it does not exist), then append the log content to the back of the log file, and finally close the log file.

In this article, we save the contents of the log in json format for easy reading directly when needed.

PHP write log files
PHP write log files need to open, write and close the file operation, PHP has fopen (), fwrite () and fclose () corresponding to the three functions, and another function file_put_contents () it can also write a string file In fact, this function in turn calls fopen (), fwrite () and fclose (). So we use file_put_contents () is very simple. It is noteworthy that, to add content to the file need to bring parameters: FILE_APPEND.

In actual operation, we may encounter log file oversized situation, so we set a maximum value, when the log file size exceeds this maximum, the log file back up, and then re-generate a new log file to record New log content.

Before writing the log, we json format the log content, so we need to convert the content to JSON format and then write the file. Of course, you can also use json, or for other tools (such as log analysis tools) can read the format. In short, we write the content is easy to read when necessary.
    function writeLog($filename,$msg){ 
        $res = array(); 
        $res['msg'] = $msg; 
        $res['logtime'] = date("Y-m-d H:i:s",time()); 
 
        //Back up the log file if the log file exceeds the specified size
        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); 
        } 
 
        //To the log file content append log content
        file_put_contents($filename, $content, FILE_APPEND); 
    } 


PHP read log files
When necessary, we will read the contents of the log analysis, the same we use the PHP file_get_contents () function, read the content directly, and converted into json format, easy to call.
    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
The function of writing and reading the log we often need to use, so I will write and read functions into a class, easy to call.
<?php  
/* 
* Log class
* Generate a daily log file, backup the log file and rebuild the new log file when the file exceeds the specified size
*/ 
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()); 
 
        //Back up the log file if the log file exceeds the specified size
        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); 
        } 
 
        //To the log file content append log content
        file_put_contents($filename, $content, FILE_APPEND); 
    } 
 
 
    //Read the 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; 
    } 
} 
 ?> 


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

Category: PHP Scripts / Skins

Dear visitor, you are browsing our website as Guest.
We strongly recommend you to register and login to view hidden contents.
<
  • 0 Comments
  • 0 Articles
19 December 2017 12:25

LelandTurcE

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
This is my first time visit at here and i am really happy to read all at one place.

Information
Comment on the news site is possible only within (days) days from the date of publication.