Cache.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2012, Union of RAD (http://union-of-rad.org)
  6. * @license http://opensource.org/licenses/bsd-license.php The BSD License
  7. */
  8. namespace lithium\analysis\logger\adapter;
  9. use lithium\util\String;
  10. /**
  11. * The `Cache` logger allows log messages to be written to cache configurations set up in
  12. * `lithium\storage\Cache`. In order to use this adapter, you must first configure a cache adapter
  13. * for it to write to, as follows:
  14. *
  15. * {{{ lithium\storage\Cache::config(array(
  16. * 'storage' => array('adapter' => 'Redis', 'host' => '127.0.0.1:6379')
  17. * ));}}}
  18. *
  19. * Then, you can configure the `Cache` logger with the `'storage'` config:
  20. * {{{ lithium\analysis\Logger::config(array(
  21. * 'debug' => array('adapter' => 'Cache', 'config' => 'storage')
  22. * ));
  23. * }}}
  24. *
  25. * You can then send messages to the logger which will be written to the cache store:
  26. * {{{
  27. * lithium\analysis\Logger::write('debug', 'This message will be written to a Redis data store.');
  28. * }}}
  29. *
  30. * @see lithium\storage\Cache
  31. */
  32. class Cache extends \lithium\core\Object {
  33. /**
  34. * Classes used by `Cache`.
  35. *
  36. * @var array
  37. */
  38. protected $_classes = array(
  39. 'cache' => 'lithium\storage\Cache'
  40. );
  41. /**
  42. * Class constructor.
  43. *
  44. * @param array $config
  45. */
  46. public function __construct(array $config = array()) {
  47. $defaults = array(
  48. 'config' => null,
  49. 'expiry' => '+999 days',
  50. 'key' => 'log_{:type}_{:timestamp}'
  51. );
  52. parent::__construct($config + $defaults);
  53. }
  54. /**
  55. * Writes the message to the configured cache adapter.
  56. *
  57. * @param string $type
  58. * @param string $message
  59. * @return closure Function returning boolean `true` on successful write, `false` otherwise.
  60. */
  61. public function write($type, $message) {
  62. $config = $this->_config + $this->_classes;
  63. return function($self, $params) use ($config) {
  64. $params += array('timestamp' => strtotime('now'));
  65. $key = $config['key'];
  66. $key = is_callable($key) ? $key($params) : String::insert($key, $params);
  67. $cache = $config['cache'];
  68. return $cache::write($config['config'], $key, $params['message'], $config['expiry']);
  69. };
  70. }
  71. }
  72. ?>