1: <?php
2:
3: namespace Guzzle\Plugin\Backoff;
4:
5: use Guzzle\Common\Event;
6: use Guzzle\Log\LogAdapterInterface;
7: use Guzzle\Log\MessageFormatter;
8: use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9:
10: /**
11: * Logs backoff retries triggered from the BackoffPlugin
12: *
13: * Format your log messages using a template that can contain template substitutions found in {@see MessageFormatter}.
14: * In addition to the default template substitutions, there is also:
15: *
16: * - retries: The number of times the request has been retried
17: * - delay: The amount of time the request is being delayed
18: */
19: class BackoffLogger implements EventSubscriberInterface
20: {
21: /**
22: * @var string Default log message template
23: */
24: const DEFAULT_FORMAT = '[{ts}] {method} {url} - {code} {phrase} - Retries: {retries}, Delay: {delay}, Time: {connect_time}, {total_time}, cURL: {curl_code} {curl_error}';
25:
26: /**
27: * @var LogAdapterInterface Logger used to log retries
28: */
29: protected $logger;
30:
31: /**
32: * @var MessageFormatter Formatter used to format log messages
33: */
34: protected $formatter;
35:
36: /**
37: * Backoff retry logger
38: *
39: * @param LogAdapterInterface $logger Logger used to log the retries
40: * @param MessageFormatter $formatter Formatter used to format log messages
41: */
42: public function __construct(LogAdapterInterface $logger, MessageFormatter $formatter = null)
43: {
44: $this->logger = $logger;
45: $this->formatter = $formatter ?: new MessageFormatter(self::DEFAULT_FORMAT);
46: }
47:
48: /**
49: * {@inheritdoc}
50: */
51: public static function getSubscribedEvents()
52: {
53: return array(BackoffPlugin::RETRY_EVENT => 'onRequestRetry');
54: }
55:
56: /**
57: * Set the template to use for logging
58: *
59: * @param string $template Log message template
60: *
61: * @return self
62: */
63: public function setTemplate($template)
64: {
65: $this->formatter->setTemplate($template);
66:
67: return $this;
68: }
69:
70: /**
71: * Called when a request is being retried
72: *
73: * @param Event $event Event emitted
74: */
75: public function onRequestRetry(Event $event)
76: {
77: $this->logger->log($this->formatter->format(
78: $event['request'],
79: $event['response'],
80: $event['handle'],
81: array(
82: 'retries' => $event['retries'],
83: 'delay' => $event['delay']
84: )
85: ));
86: }
87: }
88: