» » 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: 299

12
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
13 November 2017 04:51

LiannaWhamn

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Народ на ютубе нашла способ как играть в современные игры без скачивания и установки на компьютер
через сервис Playkey, а так же нашла Генератор промокодов для сервиса Playkey ТУТ видео.
А сам Генератор промокодов ТУТ. Кто тестил сервис и Генератор отпишитесь стоит ли заморочки :):):)

<
  • 0 Comments
  • 0 Articles
22 November 2017 23:17

Pinkman

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
I have read your code helpful for me.I admire the valuable information you offer in your post. Thanks for posting it. Voyance amour par téléphone.

<
  • 0 Comments
  • 0 Articles
23 November 2017 11:40

Britney

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Amzing coding you have created in your post and it will be hlpful here best someone write my essay for me online service and get more expertise in same skill.

<
  • 0 Comments
  • 0 Articles
24 November 2017 18:32

Cesar Madisyn

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
I didn't know earlier that reading those files on PHP was a possibility. Thanks for this edubirdie review and the informative post was really helpful. I'm happy with the whole of it.

<
  • 0 Comments
  • 0 Articles
28 November 2017 20:48

Clark

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
My first time to visit in the post. In the post is very interesting and informative for me. I am glad to know that the article is really very good. I am appreciate in the work. Thanks for sharing in the post. keep it up.
trolley wheels uk

<
  • 0 Comments
  • 0 Articles
29 November 2017 18:16

Jim

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Very well written tutorial about PHP, you have work hard in making this post. I have learned a lot from this tutorial which will help me a lot in future.
Click to buy epdm rubber roofing

<
  • 0 Comments
  • 0 Articles
30 November 2017 22:09

Ellie

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Thanks for sharing this information. I was looking for this to get it into a write my research paper for me I'm getting written from a friend.

<
  • 0 Comments
  • 0 Articles
3 December 2017 20:25

Keithler

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
<a href="https://www.carbatterybuy.men/car-battery-elantra/type-017-car-batter
y-720cca-12v-90ah-bosch-3-years-wty-sealed-oem-replacement.php">Type 017 Car Battery 720CCA 12V 90Ah Bosch 3 Years Wty Sealed OEM Replacement</a>
Mitsubishi Space Star Dg A 1998-2004 Banner Starting Bull 55Ah Battery Replace
<a href="https://www.costcarbattery.date/car-battery-accessories/skoda-octavia
-1u2-1u5-2001-2004-banner-power-bull-72ah-battery-replacement.php">Skoda
Octavia 1U2 1U5 2001-2004 Banner Power Bull 72Ah Battery Replacement</a>
Peugeot 308 Cc 2009-2016 Vetech Battery 70Ah Electrical System Replacement Part
<a href="https://www.carbatteryprice.loan/car-battery-electricity-converter/fo
rd-focus-c-max-2003-2007-banner-starting-bull-60ah-electrical-battery-replace.ph
p">Ford Focus C-Max 2003-2007 Banner Starting Bull 60Ah Electrical Battery Replace</a>
Renault Clio B/C57 5/357 Mk2 Mk4 1990-2016 Banner Starting Bull 44Ah
<a href="https://www.pricecarbattery.win/car-battery-and-compressor/ford-focus
-daw-dbw-dfw-dnw-mk2-mk3-1998-2016-banner-power-bull-72ah.php">Ford Focus Daw Dbw Dfw Dnw Mk2 Mk3 1998-2016 Banner Power Bull 72Ah</a>
Fits Hyundai Terracan Hp 2001-2006 Banner Starting Bull 95Ah Battery Replace

<
  • 0 Comments
  • 0 Articles
4 December 2017 11:58

JamesExpag

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
many pills come viagra prescription
<a href="http://viagrajnmeo.com/#">viagra without a doctor’s prescription</a>
generic viagra in the usa
viagra without a doctor’s prescription
price of viagra in sri lanka

<
  • 0 Comments
  • 0 Articles
4 December 2017 12:52

Robertvar

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
sildenafil 50 mg masticable
<a href="http://viagrajnmeo.com/#">viagra without a prescription</a>
buy viagra on the net
viagra without a doctor
legal age buy viagra

<
  • 0 Comments
  • 0 Articles
5 December 2017 02:47

JefferyRed

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
viagra 50mg and 100mg
<a href="http://viagrajnmeo.com/#">viagra without a prescription</a>
viagra levitra cialis online
viagra without prescription
generic names viagra joke

<
  • 0 Comments
  • 0 Articles
Yesterday, 06:57

Evelynlon

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
payday loans online
online loans
<a href="https://smajloans.com/">payday loans</a>
cash advance loans


Add comments

Name:*
E-Mail:
Comment:
Bold Italic Underline Strike | Align left Center Align right | Insert smilies Insert link URLInsert protected URL Select color | Add Hidden Text Insert Quote Convert selected text from selection to Cyrillic (Russian) alphabet Insert spoiler
Security Code: *