logger.php 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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', 'none');
  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. /**
  82. * Alias for 'debug', used by PHPActiveRecord.
  83. * @codeCoverageIgnore
  84. */
  85. function log($message) {
  86. $this->debug($message);
  87. }
  88. private function process($message, $level) {
  89. if ($level <= $this->level)
  90. $this->output[] = array($message, $level);
  91. }
  92. function dumps() {
  93. $logger = $this;
  94. $output = '';
  95. foreach ($this->output as $i => $tuple) {
  96. list($message, $level) = $tuple;
  97. $i && $output .= "\n";
  98. $output .= preg_replace_callback(
  99. '/%\(([a-z-_ ]*)\)/i',
  100. function($matches) use ($logger, $message, $level) {
  101. $name = $matches[1];
  102. if ($name == 'message')
  103. return $message;
  104. if ($name == 'level')
  105. return Logger::$level_names[$level];
  106. return $logger->get_formatted_property($matches[1]);
  107. },
  108. $this->format
  109. );
  110. }
  111. return $output;
  112. }
  113. function dump($file_prefix='log') {
  114. switch ($this->dump_format) {
  115. case 'none':
  116. return;
  117. case 'plain':
  118. echo $this->dumps();
  119. break;
  120. case 'html':
  121. echo '<strong>Log:</strong><br />';
  122. echo '<pre>' . $this->dumps() . '</pre>';
  123. break;
  124. case 'file':
  125. $this->save(sprintf('%s_%s.log', $file_prefix, strftime('%d-%m-%Y_%H-%M-%S')));
  126. }
  127. }
  128. function clear() {
  129. $this->output = array();
  130. }
  131. function save($path) {
  132. if ($this->log_directory && !is_dir($this->log_directory))
  133. mkdir($this->log_directory, 0777, true);
  134. file_put_contents($this->log_directory . $path, $this->dumps());
  135. }
  136. function handle_exception(\Exception $e) {
  137. if( $e === null )
  138. return;
  139. $message = sprintf("Uncaught %s in file %s, line %d: %s\n\n%s", get_class($e),
  140. $e->getFile(), $e->getLine(), $e->getMessage(), $e->getTraceAsString());
  141. $this->critical($message);
  142. $this->dump('error');
  143. }
  144. function set_as_exception_handler() {
  145. set_exception_handler(array($this, 'handle_exception'));
  146. }
  147. function get_formatted_property($property) {
  148. if (isset($this->properties[$property]))
  149. return $this->properties[$property];
  150. switch( $property ) {
  151. case 'loglevel':
  152. return $this->get_level_name();
  153. case 'date':
  154. return strftime('%d-%m-%Y');
  155. case 'time':
  156. return strftime('%H:%M:%S');
  157. case 'datetime':
  158. return strftime('%d-%m-%Y %H:%M:%S');
  159. }
  160. throw new \InvalidArgumentException(sprintf('Invalid logging property "%s".', $property));
  161. }
  162. }
  163. ?>