Logging processes with PHP

29 November 2011

Its sometimes necessary as a developer to log and track data as it is processed either to debug or to keep a simple record of maybe who's logged in or out of your site. You could easily do this by accessing a MySQL database and adding a row, but you then have to create and maintain that database. So today I'm going to run through the steps to writing and reading a .txt log file.
The Code

In order to write and access our log file we will be using the php functions fopen() fwrite() and fclose(). find below the rules that can be passed to fopen().


Rule Description
‘r' Open for reading only; place the file pointer at the beginning of the file.
‘r+' Open for reading and writing; place the file pointer at the beginning of the file.
‘w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
‘w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
‘a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
‘a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
‘x' Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
‘x+' Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.

function log_action($message="") {
			$logfile = 'logs/log.txt';
			$new = file_exists($logfile) ? false : true;
		        if($handle = fopen($logfile, 'a')) { // append
			$timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
		        $content = "{$timestamp} | {$message}\n";
			fwrite($handle, $content);
			fclose($handle);
			if($new) { chmod($logfile, 0755); }
		  } else {

			echo "Could not open log file for writing.";

		  }
	}
Running the function

In a real application situation we could use logging to track certain aspects of an applications process, for example if I had a video upload script that sends a request to an API to encode the video once it's uploaded, then puts some data in the database, we could log at each stage of the process to check that each stage was completed successfully and that the script didn't error out.

Below is a very simple example of how to call the function.

$message = 'Posted to the database';
	log_action($message);

Reading our log file

Above is an image example of the code below minus the row highlighting and thumbnails.

Below is a quick method for displaying the contents of our log file. You can see that the data is displayed in a table for readability. in order to get each line of data we use fgets(); which will get each individual row from our log file, then using the PHP explode() function we can save the data in an array so we can then echo it in the individual table cells.

<table border="0" width="960px" cellpadding="4" cellspacing="0" style="font-family:Arial, Helvetica, sans-serif; font-size:14px;" class="pag">
  <tr style="background:#FFFFCC;">
     <td style="border-bottom:3px solid #FFCC99;">Datetime</td>
    <td style="border-bottom:3px solid #FFCC99;">Video Id</td>
    <td style="border-bottom:3px solid #FFCC99;">Stage</td>
    <td style="border-bottom:3px solid #FFCC99;">Status</td>
  </tr>
<?php
$filename = 'logs/log.txt';
$fp = fopen($filename, "r");
if($fp)
{ 

   while(!feof($fp))
   {
      $line = fgets($fp);
$data = explode('|', $line);

  echo '<tr>
     <td style="padding:5px; border-bottom:1px solid #ccc; border-right:1px solid #ccc;"">'.$data[0].'</td>
    <td style="padding:5px; border-bottom:1px solid #ccc; border-right:1px solid #ccc;"">'.$data[1].'</td>
    <td style="padding:5px; border-bottom:1px solid #ccc; border-right:1px solid #ccc;"">'.$data[2].'</td>
    <td style="padding:5px; border-bottom:1px solid #ccc; ">'.$data[3].'</td>
  </tr>';

   }
}
else
{
  echo ' unable to open file for reading ';
}
?>
</table>



Sumber : Jasa Pembuatan Website, Siakad, Simpeg dan SIM Rumah Sakit https://klatenweb.com
Selengkapnya : http://klatenweb.com/read/2011/11/29/756/Logging-processes-with-PHP.html