Go4Expert

Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   Simple Logging with PHP (http://www.go4expert.com/articles/simple-logging-php-t1036/)

pradeep 20Jul2006 19:26

Simple Logging with PHP
 
Manier times we require to create logs of various activities/errors in our web applications, so here we'll look into how to achieve that.
Logging data to a file in PHP can be as simple or as complex as you want to make it. Break it down, though, and it all comes down to these three simple lines of code:

Code: PHP

<?php
   // open file
   $fd = fopen($filename, "a");
   // write string
   fwrite($fd, $str . "\n");
   // close file
   fclose($fd);
   ?>


Fundamentally, logging data to a file consists of three steps:

  1. Open the target file (or create it if it doesn't already exist);
  2. Append your data to the end of the file;
  3. Close the file.
You can encapsulate this as a function,
Code: PHP

<?php
   function logToFile($filename, $msg)
   {
   // open file
   $fd = fopen($filename, "a");
   // write string
   fwrite($fd, $msg . "\n");
   // close file
   fclose($fd);
   }
   ?>


and then use it liberally within your code as and when required.

Code: PHP

<?php
   function logToFile($filename, $msg)
   {
   // open file
   $fd = fopen($filename, "a");
   // write string
   fwrite($fd, $msg . "\n");
   // close file
   fclose($fd);
   }
   $v = "Logging with PHP";
   if (!is_numeric($v)) { logToFile("my.log", "Non-numeric variable
 was found"
); }
   $a = array("chocolate", "strawberry", "peach");
   if (!in_array('fish', $a)) { logToFile("my.log", "No fish found"); }
   $conn = @mysql_connect("go4expert", "user", "password");
   if (!$conn)
   {
   logToFile("my.log", "Could not connect to database on go4expert");
   die("Could not connect to database on go4expert");
   }
   ?>


You can make the function a little more professional by having it automatically append the date and time of the log message to the log file as well:

Code: PHP

<?php
   function logToFile($filename, $msg)
   {
   // open file
   $fd = fopen($filename, "a");
   // append date/time to message
   $str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;
   // write string
   fwrite($fd, $str . "\n");
   // close file
   fclose($fd);
   }
   ?>


Here's an example of the output:

Code:

  [2002/11/25 06:02:42] Non-numeric variable was found
  [2002/11/25 06:02:42] No fish found
  [2002/11/25 06:02:43] Could not connect to database on go4expert



All times are GMT +5.5. The time now is 03:52.