Skip to content

Commit

Permalink
Format HTTP headers in span attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
cyve authored and cdaguerre committed Apr 23, 2024
1 parent 6c046fd commit 239fff3
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 7 deletions.
28 changes: 28 additions & 0 deletions src/Http/HttpMessageHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

/*
* This file is part of the worldia/instrumentation-bundle package.
* (c) Worldia <[email protected]>
*/

namespace Instrumentation\Http;

class HttpMessageHelper
{
/**
* @param array<string,string[]> $headers
*/
public static function formatHeadersForSpanAttribute(array $headers): string
{
$lines = [];
foreach ($headers as $name => $values) {
foreach ($values as $value) {
$lines[] = sprintf('%s: %s', mb_strtolower($name), $value);
}
}

return implode(\PHP_EOL, $lines);
}
}
8 changes: 1 addition & 7 deletions src/Http/TracedResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,13 +182,7 @@ protected function endTracing(): void

try {
if (\in_array('response.headers', $info['user_data']['span_attributes'] ?? [])) {
$headers = [];
$raw = $this->getHeaders(false);
foreach ($raw as $header => $value) {
$headers[$header] = $this->toReadableHeaderValue($value);
}

$this->span->setAttribute('response.headers', $headers);
$this->span->setAttribute('response.headers', HttpMessageHelper::formatHeadersForSpanAttribute($this->getHeaders(false)));
}

if (\in_array('response.body', $info['user_data']['span_attributes'] ?? [])) {
Expand Down
3 changes: 3 additions & 0 deletions src/Http/TracingHttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ public function request(string $method, string $url, array $options = []): Respo
if (\in_array('request.body', $options['user_data']['span_attributes'])) {
$attributes['request.body'] = self::getRequestBody($options);
}
if (\in_array('request.headers', $options['user_data']['span_attributes'])) {
$attributes['request.headers'] = HttpMessageHelper::formatHeadersForSpanAttribute($headers);
}
} catch (\Throwable) {
}

Expand Down

0 comments on commit 239fff3

Please sign in to comment.