Writer.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. /**
  3. * @file
  4. * Contains the Logger model.
  5. */
  6. namespace Redis\Logger;
  7. class Writer {
  8. const PREFIX = 'drupal:logger';
  9. /**
  10. * @var \Redis
  11. * Assumes use of Predis, not PhpRedis
  12. */
  13. protected $redis;
  14. /**
  15. * @var \Redis\Logger\Writer
  16. */
  17. protected static $instance;
  18. /**
  19. * TODO implement
  20. *
  21. * @var int
  22. * Maximum size of per-template event list. Non-empty() values enable
  23. * trimming on insert, so have a tiny performance impact: two O(1) commands
  24. * instead of one.
  25. */
  26. protected $list_limit = NULL;
  27. /**
  28. * @var bool
  29. * - true: messages are stored during the page cycle and sent on shutdown.
  30. * - false: message are sent immediately
  31. */
  32. public $deferred = FALSE;
  33. /**
  34. * @var \Redis\Logger\Entry[]
  35. */
  36. protected $entries = array();
  37. /**
  38. * @var \Redis\Logger\Settings
  39. */
  40. protected $settings;
  41. /**
  42. * Constructor.
  43. *
  44. * @param \Redis $redis
  45. */
  46. protected function __construct(\Redis $redis, Settings $settings = NULL) {
  47. $this->redis = $redis;
  48. if (!isset($settings)) {
  49. $settings = new Settings();
  50. }
  51. $this->settings = $settings;
  52. }
  53. /**
  54. * Public method to build a Logger from the singleton Redis client.
  55. *
  56. * @return static
  57. */
  58. public static function createFromGlobals() {
  59. $redis = \Redis_Client::getClient();
  60. assert('$redis instanceof \Redis');
  61. return new static($redis);
  62. }
  63. /**
  64. * Logger singleton accessor.
  65. *
  66. * @return \Redis\Logger\Writer
  67. */
  68. public static function instance() {
  69. if (!isset(static::$instance)) {
  70. static::$instance = static::createFromGlobals();
  71. }
  72. return static::$instance;
  73. }
  74. /**
  75. * @param \Redis\Logger\Entry $entry
  76. */
  77. protected function post(Entry $entry) {
  78. $list = $this->settings->getPrefix() . "{$entry->type}:{$entry->severity}:{$entry->message}";
  79. $item = serialize($entry);
  80. $this->redis->lPush($list, $item);
  81. }
  82. /**
  83. * @param \Redis\Logger\Entry $entry
  84. */
  85. public function log(Entry $entry) {
  86. if ($this->deferred) {
  87. $this->entries[] = $entry;
  88. }
  89. else {
  90. $this->post($entry);
  91. }
  92. }
  93. }