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

175
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
11 December 2017 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

<
  • 0 Comments
  • 0 Articles
12 December 2017 22:20

Katrinaanisa

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

<
  • 2 Comments
  • 0 Articles
15 December 2017 19:17

Arbazshaikh

Reply
  • Group: Members
  • РRegistered date: 1.12.2017
  • Status: Currently Offline
 
Really I enjoy your site with effective and useful information. It is included very nice post with a lot of our resources.thanks for share. i enjoy this post. http://redveinkratom.store/

<
  • 2 Comments
  • 0 Articles
16 December 2017 00:44

Arbazshaikh

Reply
  • Group: Members
  • РRegistered date: 1.12.2017
  • Status: Currently Offline
 
Wow, excellent post. I'd like to draft like this too - taking time and real hard work to make a great article. This post has encouraged me to write some posts that I am going to write soon. <a href="http://greenmalaysiankratom.com/">http://greenmalaysiankratom
.com/</a>

<
  • 0 Comments
  • 0 Articles
17 December 2017 08:17

Rosettabrada

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

<
  • 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.

<
  • 0 Comments
  • 0 Articles
20 December 2017 19:37

Michaelflach

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
cialis liquid for sale
<a href="http://naqsehuki.com/#">buy cialis online</a>
order cialis online overnight
buy cialis
cialis buy in uk

<
  • 0 Comments
  • 0 Articles
23 December 2017 02:22

Williamhum

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
cheap levitra 20mg
<a href="http://levitradbws.com/#">vardenafil 20mg</a>
safe place buy levitra
levitra 20 mg
levitra buy singapore
<a href="http://vardenafilghns.com/#">levitra</a>
discount levitra online
vardenafil 20mg
buy levitra dapoxetine

<
  • 0 Comments
  • 0 Articles
23 December 2017 05:31

RonaldAlode

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
buy levitra in thailand
<a href="http://levitradbws.com/#">vardenafil 20mg</a>
buy generic levitra from canada
levitra 20 mg
buy levitra in canada
<a href="http://vardenafilghns.com/#">levitra</a>
levitra by mail order
vardenafil 20mg
discount on levitra

<
  • 0 Comments
  • 0 Articles
23 December 2017 16:13

ShannonNem

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
levitra buy australia
<a href="http://levitradbws.com/#">levitra</a>
cheap levitra professional
vardenafil 20mg
levitra sale walmart
<a href="http://vardenafilghns.com/#">levitra</a>
buy cialis and levitra
vardenafil 20mg
buy brand name levitra online

<
  • 0 Comments
  • 0 Articles
23 December 2017 18:38

Brucehoace

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
cheap levitra uk
<a href="http://levitradbws.com/#">vardenafil 20mg</a>
buy generic levitra 10 mg
vardenafil
cheapest levitra super active oo
<a href="http://vardenafilghns.com/#">vardenafil</a>
how to buy levitra
vardenafil 20mg
cheap levitra pills

<
  • 0 Comments
  • 0 Articles
24 December 2017 10:08

Thomasicefe

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
levitra professional sale
<a href="http://levitradbws.com/#">levitra</a>
buy levitra australia
levitra
buy levitra overnight shipping
<a href="http://vardenafilghns.com/#">vardenafil</a>
can you buy levitra canada
vardenafil 20mg
buy levitra toronto

buy cialis professional
<a href="hhttp://cialisyrudgj.com/#">buy generic cialis online</a>
can cialis pills be cut in half
buy generic cialis online
buy cialis without doctor prescription
<a href="http://cialisuitykh.com/#">cialis price</a>
buy cialis discount online
cheap cialis
cialis for sale online

<
  • 0 Comments
  • 0 Articles
24 December 2017 13:06

Jerrysag

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
ambien cialis eteamz.active.com generic link order
<a href="hhttp://cialisyrudgj.com/#">cialis generic</a>
buycialis.eu
generic cialis
discount cialis 20 mg
<a href="http://cialisuitykh.com/#">cialis prices</a>
cialis to buy us
cheap cialis
buying cialis in peru

<
  • 0 Comments
  • 0 Articles
24 December 2017 18:48

Kate

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
The information you share is very useful. It is closely related to my work and has helped me grow. router login

<
  • 0 Comments
  • 0 Articles
25 December 2017 00:24

Lionelagelp

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
cialis for sale online
<a href="hhttp://cialisyrudgj.com/#">buy generic cialis online</a>
cialis pills picture
cialis generic
buy cialis from europe
<a href="http://cialisuitykh.com/#">cheap cialis</a>
cialis online for sale
cialis price
how to order cialis online safely

<
  • 0 Comments
  • 0 Articles
25 December 2017 02:53

Robertnug

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
cialis sale toronto
<a href="hhttp://cialisyrudgj.com/#">cialis generic</a>
buy cialis online with mastercard
buy generic cialis online
cialis buy now
<a href="http://cialisuitykh.com/#">cheap cialis</a>
cialis wholesale
cialis price
cialis buy generic

<
  • 0 Comments
  • 0 Articles
25 December 2017 12:59

Bruceprard

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
prezzo viagra 50 mg
<a href="http://viagratutrjdsd.com/#">buy viagra online pharmacy</a>
viagra 100mg filmtabletten nebenwirkungen
buy viagra online pharmacy
cheap generic viagra uk online
<a href="http://viagraeyefbdj.com/#">viagra online pharmacy</a>
does generic viagra work good
viagra online
sildenafil citrate sublingual tablets 100 mg

<
  • 0 Comments
  • 0 Articles
25 December 2017 15:24

Georgemer

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
viagra from boots online
<a href="http://viagratutrjdsd.com/#">viagra online</a>
can i take 150mg viagra
viagra online pharmacy
sildenafil dosis 100 mg
<a href="http://viagraeyefbdj.com/#">viagra online pharmacy</a>
is generic viagra approved by the fda
online viagra
buy viagra next day

<
  • 0 Comments
  • 0 Articles
26 December 2017 15:04

AlbertMaisK

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
cialis buy with paypal
<a href="http://cialisietwdffjj.com/#">cialis best price</a>
order viagra cialis online
cialis price
buy cialis and levitra
<a href="http://cialisytigjtuj.com/#">cialis price</a>
buy cialis brand name
cialis prices
cheapest place to buy cialis online

Previous Next

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: *