Logging class (Log messages to a file)


/ Published in: PHP
Save to your folder(s)

This class can log messages to a file. If the log file becomes too large (over 1MB), the class will archive it and will create new. If there are archives older than one month, they will be deleted automatically.
In the future versions I will add the opportunity to set max log size and max time to keep the archives.


Copy this code and paste it in your HTML
  1. <?php
  2. class logger {
  3. private $file;
  4. private $error = false;
  5.  
  6. function __construct($file) {
  7. if(file_exists($file) && ((filesize($file) / 1024) > 1024)) {
  8. $dirname = dirname($file);
  9. $filename = basename($file);
  10. $newname = $dirname.'/'.date('d.m.Y').'_'.$filename;
  11. if(!rename($file, $newname)) {
  12. $this->error = 'Can\'t rename the old log file';
  13. }
  14. foreach (glob($dirname.'/*.log') as $logfile) {
  15. //ако има стари логове на повече от 1 месец
  16. if(filemtime($logfile) < (time() - (30 * 24 * 3600))) {
  17. unlink($logfile);
  18. }
  19. }
  20. file_put_contents($file, '');
  21. }
  22. elseif(!file_exists($file)) {
  23. file_put_contents($file, '');
  24. }
  25. $this->file = $file;
  26. }
  27.  
  28. function log_start() {
  29. $msg_start = 'Start time: '.date('d.m.Y h:i:s').PHP_EOL;
  30. if(!file_put_contents($this->file, $msg_start, FILE_APPEND)) {
  31. $this->error = 'Can\'t write to log';
  32. }
  33. }
  34.  
  35. function log_message($message) {
  36. $message = $message.PHP_EOL;
  37. if(!file_put_contents($this->file, $message, FILE_APPEND)) {
  38. $this->error = 'Can\'t write to log';
  39. }
  40. }
  41.  
  42. function log_end() {
  43. $msg_end = 'End time: '.date('d.m.Y h:i:s').PHP_EOL;
  44. $msg_end .= '-------------------------------'.PHP_EOL;
  45. if(!file_put_contents($this->file, $msg_end, FILE_APPEND)) {
  46. $this->error = 'Can\'t write to log';
  47. }
  48. }
  49.  
  50. function is_error() {
  51. if($this->error != false) {
  52. return true;
  53. }
  54. return false;
  55. }
  56.  
  57. function get_error() {
  58. return $this->error;
  59. }
  60. }
  61. /*
  62. example usage
  63.  
  64. $log = new logger('/path/to/log.txt'); //if file doesnt exiists, will be created
  65. $log->log_start(); //this will insert timestap to mark the beginning
  66. if($sallary < $work) {
  67. $log->log_message('Not acceptable sallary/work ratio');
  68. }
  69. $log->log_end(); //this will insert timestap to mark the end of current log
  70.  
  71. */
  72. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.