Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Sentry logs #1813

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@
*/
private $checkIn;

/**
* @var array|null
*/
private $logs;

Check failure on line 67 in src/Event.php

View workflow job for this annotation

GitHub Actions / PHPStan

Property Sentry\Event::$logs type has no value type specified in iterable type array.

/**
* @var string|null The name of the server (e.g. the host name)
*/
Expand Down Expand Up @@ -216,6 +221,11 @@
return new self($eventId, EventType::checkIn());
}

public static function createLogs(?EventId $eventId = null): self
{
return new self($eventId, EventType::logs());
}

/**
* @deprecated Metrics are no longer supported. Metrics API is a no-op and will be removed in 5.x.
*/
Expand Down Expand Up @@ -368,6 +378,18 @@
return $this;
}

public function getLogs(): array

Check failure on line 381 in src/Event.php

View workflow job for this annotation

GitHub Actions / PHPStan

Method Sentry\Event::getLogs() return type has no value type specified in iterable type array.
{
return $this->logs;

Check failure on line 383 in src/Event.php

View workflow job for this annotation

GitHub Actions / PHPStan

Method Sentry\Event::getLogs() should return array but returns array|null.
}

public function setLogs(array $logs): self

Check failure on line 386 in src/Event.php

View workflow job for this annotation

GitHub Actions / PHPStan

Method Sentry\Event::setLogs() has parameter $logs with no value type specified in iterable type array.
{
$this->logs = $logs;

return $this;
}

/**
* @deprecated Metrics are no longer supported. Metrics API is a no-op and will be removed in 5.x.
*/
Expand Down
6 changes: 6 additions & 0 deletions src/EventType.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ public static function checkIn(): self
return self::getInstance('check_in');
}

public static function logs(): self
{
return self::getInstance('log');
}

/**
* @deprecated Metrics are no longer supported. Metrics API is a no-op and will be removed in 5.x.
*/
Expand All @@ -61,6 +66,7 @@ public static function cases(): array
self::event(),
self::transaction(),
self::checkIn(),
self::logs(),
self::metrics(),
];
}
Expand Down
42 changes: 42 additions & 0 deletions src/Logs/LogLevel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

declare(strict_types=1);

namespace Sentry\Logs;

class LogLevel
{
/**
* @var string The value of the enum instance
*/
private $value;

/**
* @var array<string, self> A list of cached enum instances
*/
private static $instances = [];

private function __construct(string $value)
{
$this->value = $value;
}

public static function info(): self
{
return self::getInstance('info');
}

public function __toString(): string
{
return $this->value;
}

private static function getInstance(string $value): self
{
if (!isset(self::$instances[$value])) {
self::$instances[$value] = new self($value);
}

return self::$instances[$value];
}
}
44 changes: 44 additions & 0 deletions src/Logs/Logs.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

declare(strict_types=1);

namespace Sentry\Logs;

use Sentry\EventId;

class Logs
{
/**
* @var self|null
*/
private static $instance;

/**
* @var LogsAggregator
*/
private $aggregator;

private function __construct()
{
$this->aggregator = new LogsAggregator();
}

public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new self();
}

return self::$instance;
}

public function info(string $message): void
{
$this->aggregator->add(LogLevel::info(), $message);
}

public function flush(): ?EventId
{
return $this->aggregator->flush();
}
}
96 changes: 96 additions & 0 deletions src/Logs/LogsAggregator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php

declare(strict_types=1);

namespace Sentry\Logs;

use Sentry\Event;
use Sentry\EventId;
use Sentry\SentrySdk;
use Sentry\State\Scope;
use Sentry\Tracing\TransactionSource;

/**
* @internal
*/
final class LogsAggregator
{
private $logs = [];

Check failure on line 18 in src/Logs/LogsAggregator.php

View workflow job for this annotation

GitHub Actions / PHPStan

Property Sentry\Logs\LogsAggregator::$logs has no type specified.

public function add(
LogLevel $level,
string $message,
): void {
$timestamp = time();
$traceId = null;

$hub = SentrySdk::getCurrentHub();
$span = $hub->getSpan();
if ($span !== null) {
$traceId = $span->getTraceId();
}

$this->logs[] = [
'timestamp' => $timestamp,
'trace_id' => (string) $traceId,
'level' => (string) $level,
'body' => $message,
];
}

public function flush(): ?EventId
{
if (empty($this->logs)) {
return null;
}

$hub = SentrySdk::getCurrentHub();
$event = Event::createLogs()->setLogs($this->logs);

$this->logs = [];

return $hub->captureEvent($event);
}

/**
* @param array<string, string> $tags
*
* @return array<string, string>
*/
private function serializeTags(array $tags): array

Check failure on line 60 in src/Logs/LogsAggregator.php

View workflow job for this annotation

GitHub Actions / PHPStan

Method Sentry\Logs\LogsAggregator::serializeTags() is unused.
{
$hub = SentrySdk::getCurrentHub();
$client = $hub->getClient();

if ($client !== null) {
$options = $client->getOptions();

$defaultTags = [
'environment' => $options->getEnvironment() ?? Event::DEFAULT_ENVIRONMENT,
];

$release = $options->getRelease();
if ($release !== null) {
$defaultTags['release'] = $release;
}

$hub->configureScope(function (Scope $scope) use (&$defaultTags) {
$transaction = $scope->getTransaction();
if (
$transaction !== null
// Only include the transaction name if it has good quality
&& $transaction->getMetadata()->getSource() !== TransactionSource::url()
) {
$defaultTags['transaction'] = $transaction->getName();
}
});

$tags = array_merge($defaultTags, $tags);
}

// It's very important to sort the tags in order to obtain the same bucket key.
ksort($tags);

return $tags;
}
}
31 changes: 31 additions & 0 deletions src/Serializer/EnvelopItems/LogsItem.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace Sentry\Serializer\EnvelopItems;

use Sentry\Event;
use Sentry\Util\JSON;

/**
* @internal
*/
class LogsItem implements EnvelopeItemInterface
{
public static function toEnvelopeItem(Event $event): string
{
$header = [
'type' => (string) $event->getType(),
'content_type' => 'application/json',
];

$payload = '';

$logs = $event->getLogs();
foreach ($logs as $log) {
$payload .= \sprintf("%s\n%s", JSON::encode($header), JSON::encode($log));
}

return $payload;
}
}
4 changes: 4 additions & 0 deletions src/Serializer/PayloadSerializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Sentry\Options;
use Sentry\Serializer\EnvelopItems\CheckInItem;
use Sentry\Serializer\EnvelopItems\EventItem;
use Sentry\Serializer\EnvelopItems\LogsItem;
use Sentry\Serializer\EnvelopItems\ProfileItem;
use Sentry\Serializer\EnvelopItems\TransactionItem;
use Sentry\Tracing\DynamicSamplingContext;
Expand Down Expand Up @@ -77,6 +78,9 @@ public function serialize(Event $event): string
case EventType::checkIn():
$items = CheckInItem::toEnvelopeItem($event);
break;
case EventType::logs():
$items = LogsItem::toEnvelopeItem($event);
break;
}

return \sprintf("%s\n%s", JSON::encode($envelopeHeader), $items);
Expand Down
6 changes: 6 additions & 0 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Psr\Log\LoggerInterface;
use Sentry\HttpClient\HttpClientInterface;
use Sentry\Integration\IntegrationInterface;
use Sentry\Logs\Logs;
use Sentry\Metrics\Metrics;
use Sentry\State\Scope;
use Sentry\Tracing\PropagationContext;
Expand Down Expand Up @@ -377,6 +378,11 @@ function continueTrace(string $sentryTrace, string $baggage): TransactionContext
return TransactionContext::fromHeaders($sentryTrace, $baggage);
}

function logger(): Logs
{
return Logs::getInstance();
}

/**
* @deprecated Metrics are no longer supported. Metrics API is a no-op and will be removed in 5.x.
*/
Expand Down
Loading