logger.php 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. <?php
  2. /**
  3. * Logging functions.
  4. *
  5. * @author Taddeus Kroes
  6. * @date 13-07-2012
  7. */
  8. namespace WebBasics;
  9. require_once 'base.php';
  10. /**
  11. * Logger class.
  12. *
  13. * A Logger object provides five functions to process log messages.
  14. *
  15. * @package WebBasics
  16. */
  17. class Logger extends Base {
  18. const CRITICAL = 0;
  19. const ERROR = 1;
  20. const WARNING = 2;
  21. const INFO = 3;
  22. const DEBUG = 4;
  23. static $level_names = array('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG');
  24. private static $allowed_dump_formats = array('plain', 'html', 'file');
  25. const DEFAULT_FORMAT = '%(datetime): %(level): %(message)';
  26. private $properties = array();
  27. private $output = array();
  28. private $format = self::DEFAULT_FORMAT;
  29. private $level = self::WARNING;
  30. private $dump_format = 'plain';
  31. private $log_directory = '';
  32. function set_directory($directory) {
  33. $this->log_directory = self::path_with_slash($directory);
  34. }
  35. function set_dump_format($format) {
  36. if( !in_array($format, self::$allowed_dump_formats) )
  37. throw new \InvalidArgumentException(sprintf('', $format));
  38. $this->dump_format = $format;
  39. }
  40. function set_format($format) {
  41. $this->format = (string)$format;
  42. }
  43. function get_format() {
  44. return $this->format;
  45. }
  46. function get_level() {
  47. return $this->level;
  48. }
  49. function get_level_name() {
  50. return self::$level_names[$this->level];
  51. }
  52. function set_level($level) {
  53. if( is_string($level) ) {
  54. $level = strtoupper($level);
  55. if( !defined('self::'.$level) )
  56. throw new \InvalidArgumentException(sprintf('Invalid debug level %s.', $level));
  57. $level = constant('self::'.$level);
  58. }
  59. if( $level < self::CRITICAL || $level > self::DEBUG )
  60. throw new \InvalidArgumentException(sprintf('Invalid debug level %d.', $level));
  61. $this->level = $level;
  62. }
  63. function set_property($name, $value) {
  64. $this->properties[$name] = (string)$value;
  65. }
  66. function critical($message) {
  67. $this->process($message, self::CRITICAL);
  68. }
  69. function error($message) {
  70. $this->process($message, self::ERROR);
  71. }
  72. function warning($message) {
  73. $this->process($message, self::WARNING);
  74. }
  75. function info($message) {
  76. $this->process($message, self::INFO);
  77. }
  78. function debug($message) {
  79. $this->process($message, self::DEBUG);
  80. }
  81. private function process($message, $level) {
  82. if( $level <= $this->level )
  83. $this->output[] = array($message, $level);
  84. }
  85. function dumps() {
  86. $logger = $this;
  87. $output = '';
  88. foreach( $this->output as $i => $tuple ) {
  89. list($message, $level) = $tuple;
  90. $i && $output .= "\n";
  91. $output .= preg_replace_callback(
  92. '/%\(([a-z-_ ]*)\)/i',
  93. function ($matches) use ($logger, $message, $level) {
  94. $name = $matches[1];
  95. if( $name == 'message' )
  96. return $message;
  97. if( $name == 'level' )
  98. return Logger::$level_names[$level];
  99. return $logger->get_formatted_property($matches[1]);
  100. },
  101. $this->format
  102. );
  103. }
  104. return $output;
  105. }
  106. function dump($file_prefix='log') {
  107. switch( $this->dump_format ) {
  108. case 'plain':
  109. echo $this->dumps();
  110. break;
  111. case 'html':
  112. echo '<strong>Log:</strong><br />';
  113. echo '<pre>' . $this->dumps() . '</pre>';
  114. break;
  115. case 'file':
  116. $this->save(sprintf('%s_%s.log', $file_prefix, strftime('%d-%m-%Y_%H-%M-%S')));
  117. }
  118. }
  119. function clear() {
  120. $this->output = array();
  121. }
  122. function save($path) {
  123. if( $this->log_directory && !is_dir($this->log_directory) )
  124. mkdir($this->log_directory, 0644, true);
  125. file_put_contents($this->log_directory . $path, $this->dumps());
  126. }
  127. function handle_exception(\Exception $e) {
  128. if( $e === null )
  129. return;
  130. $message = sprintf("Uncaught %s in file %s, line %d: %s\n\n%s", get_class($e),
  131. $e->getFile(), $e->getLine(), $e->getMessage(), $e->getTraceAsString());
  132. $this->critical($message);
  133. $this->dump('error');
  134. }
  135. function set_as_exception_handler() {
  136. set_exception_handler(array($this, 'handle_exception'));
  137. }
  138. function get_formatted_property($property) {
  139. if( isset($this->properties[$property]) )
  140. return $this->properties[$property];
  141. switch( $property ) {
  142. case 'loglevel':
  143. return $this->get_level_name();
  144. case 'date':
  145. return strftime('%d-%m-%Y');
  146. case 'time':
  147. return strftime('%H:%M:%S');
  148. case 'datetime':
  149. return strftime('%d-%m-%Y %H:%M:%S');
  150. }
  151. throw new \InvalidArgumentException(sprintf('Invalid logging property "%s".', $property));
  152. }
  153. }
  154. ?>