|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Sentry\Logs; |
| 6 | + |
| 7 | +use Sentry\Event; |
| 8 | +use Sentry\EventId; |
| 9 | +use Sentry\SentrySdk; |
| 10 | +use Sentry\State\Scope; |
| 11 | +use Sentry\Tracing\TransactionSource; |
| 12 | + |
| 13 | +/** |
| 14 | + * @internal |
| 15 | + */ |
| 16 | +final class LogsAggregator |
| 17 | +{ |
| 18 | + private $logs = []; |
| 19 | + |
| 20 | + public function add( |
| 21 | + LogLevel $level, |
| 22 | + string $message, |
| 23 | + ): void { |
| 24 | + $timestamp = time(); |
| 25 | + $traceId = null; |
| 26 | + |
| 27 | + $hub = SentrySdk::getCurrentHub(); |
| 28 | + $span = $hub->getSpan(); |
| 29 | + if ($span !== null) { |
| 30 | + $traceId = $span->getTraceId(); |
| 31 | + } |
| 32 | + |
| 33 | + $this->logs[] = [ |
| 34 | + 'timestamp' => $timestamp, |
| 35 | + 'trace_id' => (string) $traceId, |
| 36 | + 'level' => (string) $level, |
| 37 | + 'body' => $message, |
| 38 | + ]; |
| 39 | + } |
| 40 | + |
| 41 | + public function flush(): ?EventId |
| 42 | + { |
| 43 | + if (empty($this->logs)) { |
| 44 | + return null; |
| 45 | + } |
| 46 | + |
| 47 | + $hub = SentrySdk::getCurrentHub(); |
| 48 | + $event = Event::createLogs()->setLogs($this->logs); |
| 49 | + |
| 50 | + $this->logs = []; |
| 51 | + |
| 52 | + return $hub->captureEvent($event); |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * @param array<string, string> $tags |
| 57 | + * |
| 58 | + * @return array<string, string> |
| 59 | + */ |
| 60 | + private function serializeTags(array $tags): array |
| 61 | + { |
| 62 | + $hub = SentrySdk::getCurrentHub(); |
| 63 | + $client = $hub->getClient(); |
| 64 | + |
| 65 | + if ($client !== null) { |
| 66 | + $options = $client->getOptions(); |
| 67 | + |
| 68 | + $defaultTags = [ |
| 69 | + 'environment' => $options->getEnvironment() ?? Event::DEFAULT_ENVIRONMENT, |
| 70 | + ]; |
| 71 | + |
| 72 | + $release = $options->getRelease(); |
| 73 | + if ($release !== null) { |
| 74 | + $defaultTags['release'] = $release; |
| 75 | + } |
| 76 | + |
| 77 | + $hub->configureScope(function (Scope $scope) use (&$defaultTags) { |
| 78 | + $transaction = $scope->getTransaction(); |
| 79 | + if ( |
| 80 | + $transaction !== null |
| 81 | + // Only include the transaction name if it has good quality |
| 82 | + && $transaction->getMetadata()->getSource() !== TransactionSource::url() |
| 83 | + ) { |
| 84 | + $defaultTags['transaction'] = $transaction->getName(); |
| 85 | + } |
| 86 | + }); |
| 87 | + |
| 88 | + $tags = array_merge($defaultTags, $tags); |
| 89 | + } |
| 90 | + |
| 91 | + // It's very important to sort the tags in order to obtain the same bucket key. |
| 92 | + ksort($tags); |
| 93 | + |
| 94 | + return $tags; |
| 95 | + } |
| 96 | +} |
0 commit comments