ARedisLogRoute.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * A log route that allows log items to be stored or broadcast by redis.
  4. * @author Charles Pick
  5. * @package packages.redis
  6. */
  7. class ARedisLogRoute extends CLogRoute {
  8. /**
  9. * The name of the redis key to use when storing logs
  10. * @var string
  11. */
  12. public $redisKey;
  13. /**
  14. * Whether to broadcast log messages via pub/sub instead of saving them
  15. * @var boolean
  16. */
  17. public $useChannel = false;
  18. /**
  19. * Holds the redis connection
  20. * @var ARedisConnection
  21. */
  22. protected $_connection;
  23. /**
  24. * Sets the redis connection to use for caching
  25. * @param ARedisConnection|string $connection the redis connection, if a string is provided, it is presumed to be a the name of an applciation component
  26. */
  27. public function setConnection($connection)
  28. {
  29. if (is_string($connection)) {
  30. $connection = Yii::app()->{$connection};
  31. }
  32. $this->_connection = $connection;
  33. }
  34. /**
  35. * Gets the redis connection to use for caching
  36. * @return ARedisConnection
  37. */
  38. public function getConnection()
  39. {
  40. if ($this->_connection === null) {
  41. if (!isset(Yii::app()->redis)) {
  42. throw new CException(get_class($this)." expects a 'redis' application component");
  43. }
  44. $this->_connection = Yii::app()->redis;
  45. }
  46. return $this->_connection;
  47. }
  48. /**
  49. * Stores or broadcasts log messages via redis.
  50. * @param array $logs list of log messages
  51. */
  52. protected function processLogs($logs)
  53. {
  54. $redis = $this->getConnection()->getClient();
  55. if (function_exists("json_encode")) {
  56. $useCJSON = false;
  57. }
  58. else {
  59. $useCJSON = true;
  60. }
  61. foreach($logs as $log) {
  62. $item = array(
  63. "level" => $log[1],
  64. "category" => $log[2],
  65. "time" => $log[3],
  66. "message" => $log[0],
  67. );
  68. if ($useCJSON) {
  69. $json = CJSON::encode($item);
  70. }
  71. else {
  72. $json = json_encode($item);
  73. }
  74. if ($this->useChannel) {
  75. $redis->publish($this->redisKey, $json);
  76. }
  77. else {
  78. $redis->zAdd($this->redisKey,$log[3],$json);
  79. }
  80. }
  81. }
  82. }