logger.php 4.3 KB

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