Posted By

Sverri on 08/29/10


Tagged

log


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

wireplay


Log Class


 / Published in: PHP
 

A nice and simple class for logging events. Stores events in files based on the date (yyyy-mm-dd.txt) and prefaces each entry with the time it was stored (hh:mm:ss ...).

  1. class Log
  2. {
  3. // Change the path to the folder where your logs will be stored
  4. // The "%s" will be replaced with the date (yyyy-mm-dd)
  5. private $file = '/php-logs/%s.txt';
  6.  
  7. // The date will be used for the filename, so no spaces, slashes, etc...
  8. private $date = 'Y-m-d';
  9.  
  10. // Entries will be prefaced with the time
  11. private $time = 'H:i:s';
  12.  
  13. // Adds message to the end of the appropriate file
  14. public function save($message)
  15. {
  16. // Get the date and time
  17. list($date, $time) = explode('/', date("$this->date/$this->time"));
  18.  
  19. // Construct the entry
  20. $entry = "$time $message\n";
  21.  
  22. // Get the file we want to write to
  23. $file = sprintf($this->file, $date);
  24.  
  25. // Get a handle on the file and place the pointer at the end
  26. if (($handle = fopen($file, 'a')) !== false)
  27. {
  28. // Write entry to the file
  29. $result = fwrite($handle, $entry);
  30. }
  31. // Close the file
  32. fclose($handle);
  33.  
  34. // Return the result of the operation
  35. return ($result !== false) ? true : false;
  36. }
  37. }
  38.  
  39. // Example
  40.  
  41. $log = new Log();
  42.  
  43. $error = 'There was a terrible error!';
  44.  
  45. if ($error)
  46. {
  47. // Will output in /php-logs/2010-08-28.txt:
  48. //
  49. // 18:00:00 There was a terrible error!
  50. //
  51. $log->save($error);
  52. }

Report this snippet  

You need to login to post a comment.