Logger.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. <?php
  2. namespace PicoFeed\Logging;
  3. use DateTime;
  4. use DateTimeZone;
  5. /**
  6. * Logging class.
  7. *
  8. * @author Frederic Guillot
  9. */
  10. class Logger
  11. {
  12. /**
  13. * List of messages.
  14. *
  15. * @static
  16. *
  17. * @var array
  18. */
  19. private static $messages = array();
  20. /**
  21. * Default timezone.
  22. *
  23. * @static
  24. *
  25. * @var string
  26. */
  27. private static $timezone = 'UTC';
  28. /**
  29. * Enable or disable logging.
  30. *
  31. * @static
  32. *
  33. * @var bool
  34. */
  35. public static $enable = false;
  36. /**
  37. * Enable logging.
  38. *
  39. * @static
  40. */
  41. public static function enable()
  42. {
  43. self::$enable = true;
  44. }
  45. /**
  46. * Add a new message.
  47. *
  48. * @static
  49. *
  50. * @param string $message Message
  51. */
  52. public static function setMessage($message)
  53. {
  54. if (self::$enable) {
  55. $date = new DateTime('now', new DateTimeZone(self::$timezone));
  56. self::$messages[] = '['.$date->format('Y-m-d H:i:s').'] '.$message;
  57. }
  58. }
  59. /**
  60. * Get all logged messages.
  61. *
  62. * @static
  63. *
  64. * @return array
  65. */
  66. public static function getMessages()
  67. {
  68. return self::$messages;
  69. }
  70. /**
  71. * Remove all logged messages.
  72. *
  73. * @static
  74. */
  75. public static function deleteMessages()
  76. {
  77. self::$messages = array();
  78. }
  79. /**
  80. * Set a different timezone.
  81. *
  82. * @static
  83. *
  84. * @see http://php.net/manual/en/timezones.php
  85. *
  86. * @param string $timezone Timezone
  87. */
  88. public static function setTimeZone($timezone)
  89. {
  90. self::$timezone = $timezone ?: self::$timezone;
  91. }
  92. /**
  93. * Get all messages serialized into a string.
  94. *
  95. * @static
  96. *
  97. * @return string
  98. */
  99. public static function toString()
  100. {
  101. return implode(PHP_EOL, self::$messages).PHP_EOL;
  102. }
  103. }