PHP logging and reading JSON format log files

Source: Internet
Author: User
Tags abs php write

We sometimes need to record the operation of a user or an action event on the back end, and you can use the back-end language such as PHP to log the results of the operation to a journal file to facilitate testing and locating problems. In particular, these are running on the back end and the front-end can not directly see the results of the operation, then log files can be recorded, if you often with a number of interface development, such as Alipay interface, micro-credit card interface, logging is essential.


The PHP logging we're talking about is writing log information to a log file that distinguishes it from the memory log. The process of writing to the log is to open the log file (newly created if it does not exist), append the log contents to the log file, and then close the log file.
In this article, we save the contents of the log in JSON format, which is easy to read directly when necessary.

PHP Write log file

PHP Write log files need to open, write and close files and other operations, PHP has fopen (), fwrite () and fclose () three functions corresponding to it, and another function file_put_contents () it can also write a string of files, In fact, this function implements the call fopen (), fwrite (), and fclose () in turn. So we use file_put_contents () very concise. It is worth noting that the append content to the file needs to take the parameters: File_append.
In actual operation, we may encounter a large log file situation, so we set a maximum, the log file size exceeds this maximum value, back up the logs file, and then regenerate a new log file to record the new log content.

Before we write the log, we format the contents of the log in JSON, so we need to convert the content into JSON format and write to the file. Of course, you can also use JSON, or replace it with a format that other tools (such as log analysis tools) can read. In short, the content we write is convenient 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 this is a new log file, remove the first character comma from the content
if (file_exists ($filename) && abs (FileSize ($filename)) >0) {
$content = ",". Json_encode ($res);
}else{
$content = Json_encode ($res);
}

Append log contents After the contents of the past logs file
File_put_contents ($filename, $content, file_append);
}
PHP Read log file
If necessary, we read the log content for analysis, and we use PHP's file_get_contents () function to read the content directly and convert it to JSON format for easy invocation.
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 write and read classes

Write and read the log function we often use, so I will write and read the function of the class, easy to invoke.
<?php
/*
* Log Class
* Generate a log file every day, back up the log file and regenerate the new log file when the file exceeds the specified size
*/
Class Log {

Private $maxsize = 1024000; Maximum file size 1M

Write to 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 this is a new log file, remove the first character comma from the content
if (file_exists ($filename) && abs (FileSize ($filename)) >0) {
$content = ",". Json_encode ($res);
}else{
$content = Json_encode ($res);
}

Append log contents After the contents of the past logs 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 = ' written in log ';
$Log = new Log (); Instantiation of
$Log->writelog ($filename, $msg); Write to log
$loglist = $Log->readlog ($filename); Read log

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.