logging.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * Logging class:
  4. * - contains lfile, lwrite and lclose public methods
  5. * - lfile sets path and name of log file
  6. * - lwrite writes message to the log file (and implicitly opens log file)
  7. * - lclose closes log file
  8. * - first call of lwrite method will open log file implicitly
  9. * - message is written with the following format: [d/M/Y:H:i:s] (script name) message
  10. */
  11. class Logging
  12. {
  13. // declare log file and file pointer as private properties
  14. private $log_file, $fp;
  15. // set log file (path and name)
  16. public function lfile($path)
  17. {
  18. $this->log_file = $path;
  19. }
  20. // write message to the log file
  21. public function lwrite($message)
  22. {
  23. // if file pointer doesn't exist, then open log file
  24. if (!$this->fp) {
  25. $this->lopen();
  26. }
  27. // define script name
  28. $script_name = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);
  29. // define current time and suppress E_WARNING if using the system TZ settings
  30. // (don't forget to set the INI setting date.timezone)
  31. $time = @date('[d/M/Y:H:i:s]');
  32. // write current time, script name and message to the log file
  33. fwrite($this->fp, "$time ($script_name) $message" . PHP_EOL);
  34. }
  35. // close log file (it's always a good idea to close a file when you're done with it)
  36. private function lopen()
  37. {
  38. // in case of Windows set default log file
  39. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  40. $log_file_default = 'c:/php/logfile.txt';
  41. } // set default log file for Linux and other systems
  42. else {
  43. $log_file_default = '/tmp/logfile.txt';
  44. }
  45. // define log file from lfile method or use previously set default
  46. $lfile = $this->log_file ? $this->log_file : $log_file_default;
  47. // open log file for writing only and place file pointer at the end of the file
  48. // (if the file does not exist, try to create it)
  49. $this->fp = fopen($lfile, 'a') or exit("Can't open $lfile!");
  50. }
  51. // open log file (private method)
  52. public function lclose()
  53. {
  54. fclose($this->fp);
  55. }
  56. public function log($level, $msg){
  57. $log_file = $_SESSION['logging']['log']['logfile'];
  58. $log_level = $_SESSION['logging']['log']['loglevel'];
  59. if ($log_level !== $level) {
  60. return;
  61. }
  62. if ($log_file) {
  63. $this->lfile($log_file);
  64. }
  65. $this->lopen();
  66. $this->lwrite("[".strtoupper($level)."] ".$msg);
  67. //close handle
  68. $this->lclose();
  69. }
  70. }
  71. //$log = new Logging();
  72. //$log->log("debug", "passed validation, ".__line__);
  73. //$log->log("debug", check_str($_POST["ivr_menu_uuid"]));
  74. ?>