This repository was archived by the owner on May 25, 2021. It is now read-only.
forked from census-instrumentation/opencensus-php
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathEventSubscriber.php
More file actions
190 lines (172 loc) · 6.05 KB
/
EventSubscriber.php
File metadata and controls
190 lines (172 loc) · 6.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
<?php
/**
* Copyright 2017 OpenCensus Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace OpenCensus\Trace\Integrations\Guzzle;
use GuzzleHttp\Message\ResponseInterface;
use GuzzleHttp\Stream\StreamInterface;
use OpenCensus\Core\Scope;
use OpenCensus\Trace\Propagator\ArrayHeaders;
use OpenCensus\Trace\Span;
use OpenCensus\Trace\Propagator\HttpHeaderPropagator;
use OpenCensus\Trace\Propagator\PropagatorInterface;
use GuzzleHttp\Event\BeforeEvent;
use GuzzleHttp\Event\EndEvent;
use GuzzleHttp\Event\SubscriberInterface;
use OpenCensus\Trace\Tracer\TracerInterface;
/**
* This class handles integration with GuzzleHttp 5. Attaching this EventSubscriber to
* your Guzzle client, will enable distrubted tracing by passing along the trace context
* header and will also create trace spans for all outgoing requests.
*
* Example:
* ```
* use GuzzleHttp\Client;
* use OpenCensus\Trace\Integrations\Guzzle\EventSubscriber;
*
* $client = new Client();
* $subscriber = new EventSubscriber();
* $client->getEmitter()->attach($subscriber);
* ```
*/
class EventSubscriber implements SubscriberInterface
{
/**
* @var PropagatorInterface
*/
private $propagator;
/**
* @var TracerInterface
*/
private $tracer;
/**
* @var bool
*/
private $logBody;
/**
* @var Scope
*/
private $scope;
/**
* @var Span
*/
private $span;
/**
* Create a new Guzzle event listener that creates trace spans and propagates the current
* trace context to the downstream request.
*
* @param TracerInterface $tracer
* @param PropagatorInterface $propagator Interface responsible for serializing trace context
* @param bool $logBody Should the body be logged in a span (up to 4096 bytes with Content-Length header set)
*/
public function __construct(TracerInterface $tracer, PropagatorInterface $propagator = null, bool $logBody = true)
{
$this->propagator = $propagator ?: new HttpHeaderPropagator();
$this->tracer = $tracer;
$this->logBody = $logBody;
}
/**
* Returns an array of event names this subscriber wants to listen to.
*
* @return array
*/
public function getEvents()
{
return [
'before' => ['onBefore'],
'end' => ['onEnd'],
];
}
/**
* Handler for the BeforeEvent request lifecycle event. Adds the current trace context
* as the trace context header. Also starts a span representing this outgoing http request.
*
* @param BeforeEvent $event Event object emitted before a request is sent
*/
public function onBefore(BeforeEvent $event)
{
$request = $event->getRequest();
$headers = new ArrayHeaders();
$this->propagator->inject($this->tracer->spanContext(), $headers);
$request->addHeaders($headers->toArray());
$attrHeaders = [];
foreach ($request->getHeaders() as $name => $values) {
$attrHeaders['request.' . $name] = implode(', ', $values);
}
$this->span = $this->tracer->startSpan([
'name' => sprintf('Guzzle: %s', $request->getHost()),
'attributes' => [
'http.method' => $request->getMethod(),
'http.uri' => $request->getUrl(),
] + $attrHeaders,
'kind' => Span::KIND_CLIENT,
'sameProcessAsParentSpan' => !empty($this->spans),
]);
$this->scope = $this->tracer->withSpan($this->span);
}
/**
* Handler for the EndEvent request lifecycle event. Ends the current span which should be
* the span started in the BeforeEvent handler.
*
* @param EndEvent $event A terminal event that is emitted when a request transaction has ended
*/
public function onEnd(EndEvent $event)
{
$response = $event->getResponse();
$exception = $event->getException();
if ($exception) {
$this->span->addAttribute('error', 'true');
$this->span->addAttribute('exception', sprintf('%s: %s', get_class($exception), $exception->getMessage()));
}
if ($response === null) {
$this->scope->close();
return;
}
$statusCode = $response->getStatusCode();
$this->span->addAttribute('http.status_code', (string)$statusCode);
// If it's an error, annotate it as such
if ($statusCode >= 400) {
$this->span->addAttribute('error', 'true');
}
if ($this->logBody) {
$this->addBody($response);
}
$attrHeaders = [];
foreach ($response->getHeaders() as $name => $values) {
$attrHeaders['response.' . $name] = implode(', ', $values);
}
$this->span->addAttributes($attrHeaders);
$this->scope->close();
}
/**
* @param ResponseInterface $response
*/
private function addBody(ResponseInterface $response)
{
$bodyLength = (int)$response->getHeader('Content-Length');
if ($bodyLength > 0 && $bodyLength <= 4096) {
$body = $response->getBody();
if ($body instanceof StreamInterface && $body->isSeekable()) {
$responseBody = (string)$response->getBody();
$body->seek(0, SEEK_SET);
} else {
$responseBody = 'Response body is not a seekable object';
}
} else {
$responseBody = 'Either Content-Length is missing, or it is bigger than 4096';
}
$this->span->addAttribute('response.body', $responseBody);
}
}