Logger.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * @file
  4. * Trivial logger for easier debug.
  5. */
  6. namespace Osinet\ClassGrapher;
  7. use Psr\Log\LoggerInterface;
  8. use Psr\Log\LoggerTrait;
  9. use Psr\Log\LogLevel;
  10. class Logger implements LoggerInterface {
  11. use LoggerTrait;
  12. /**
  13. * Map Syslog LOG_* constants to PSR/3 log levels.
  14. */
  15. public const Levels = [
  16. LOG_EMERG => LogLevel::EMERGENCY,
  17. LOG_ALERT => LogLevel::ALERT,
  18. LOG_CRIT => LogLevel::CRITICAL,
  19. LOG_ERR => LogLevel::ERROR,
  20. LOG_WARNING => LogLevel::WARNING,
  21. LOG_NOTICE => LogLevel::NOTICE,
  22. LOG_INFO => LogLevel::INFO,
  23. LOG_DEBUG => LogLevel::DEBUG,
  24. ];
  25. public $fDebugLevel;
  26. public function __construct($debugLevel = LOG_WARNING) {
  27. $this->debugLevel($debugLevel);
  28. }
  29. /**
  30. * Get or Set the current debug level.
  31. *
  32. * @param int $level
  33. * LOG_EMERG to LOG_DEBUG. If NULL, do not set it.
  34. *
  35. * @return
  36. * The value of the debug level before this function was called.
  37. */
  38. public function debugLevel($level = NULL) {
  39. $ret = $this->fDebugLevel;
  40. if (isset($level)) {
  41. if ($level < LOG_EMERG) {
  42. $level = LOG_EMERG;
  43. }
  44. if ($level > LOG_DEBUG) {
  45. $level = LOG_DEBUG;
  46. }
  47. $this->fDebugLevel = $level;
  48. }
  49. return $ret;
  50. }
  51. /**
  52. * Output a message on STDERR if its relevance is above minimum level.
  53. *
  54. * @param string $message
  55. * @param int $level
  56. * Defined in RFC 3164, section 4.1.1 "Severity". But compare with Drupal 7
  57. * WATCHDOG_* constants in includes/bootstrap.inc for an explanation about
  58. * syslog constants in PHP.
  59. */
  60. public function legacyLog($message = "\n", $level = LOG_INFO) {
  61. $psr3Level = static::Levels[$level] ?? LogLevel::ERROR;
  62. $this->log($psr3Level, $message);
  63. }
  64. /**
  65. * @param mixed $level
  66. * @param string $message
  67. * @param array $context
  68. */
  69. public function log($level, $message, array $context = []) {
  70. if ($level <= $this->fDebugLevel) {
  71. fputs(STDERR, $message);
  72. fflush(STDERR);
  73. }
  74. }
  75. }