Skip to content

Preserve and display context / extra keys properly (LogsHandler) #1018

@sebastienfontaine

Description

@sebastienfontaine

Problem Statement

Hi 👋

I've noticed a small improvement in the LogsHandler::doWrite() method.

$this->logger->info('Log_'.random_int(1000, 9999), [
    'message' => 'This is a proof of concept command.',
    'from' => 'Console Command',
]);

Currently, when logs are sent with a context, the method merges context and extra into a single flat array:

\Sentry\logger()->aggregator()->add(
    self::getLogLevelFromSeverity(
        self::getSeverityFromLevel($record['level'])
    ),
    $record['message'],
    [],
    array_merge($record['context'], $record['extra'])
);
sentry/sentry: [info] Logs item: Log_3130 {"sentry.environment":"local","sentry.server.address":"a082dca84397","sentry.message.template":"Log_3130","sentry.sdk.name":"sentry.php.laravel","sentry.sdk.version":"4.15.1","message":"This is a proof of concept command.","from":"Console Command"}

Image

This approach causes the original context key to be lost, which prevents the Sentry UI from displaying it properly in a “context” section.

Solution Brainstorm

When I wrap the context and extra in their own keys:

\Sentry\logger()->aggregator()->add(
    self::getLogLevelFromSeverity(
        self::getSeverityFromLevel($record['level'])
    ),
    $record['message'],
    [],
    [
        'context' => $record['context'],
        'extra' => $record['extra'],
    ]
);
sentry/sentry: [info] Logs item: Log_4184 {"sentry.environment":"local","sentry.server.address":"a082dca84397","sentry.message.template":"Log_4184","sentry.sdk.name":"sentry.php.laravel","sentry.sdk.version":"4.15.1","context.message":"This is a proof of concept command.","context.from":"Console Command"}

This keeps the structure intact and improves the visibility and usability of the logs in the Sentry interface.

Image


However, even with theses changes, I’ve noticed that the Sentry UI doesn’t render the context key in the Table unless we manually json_encode() it:

[
    'context' => json_encode($record['context']),
    'extra' => json_encode($record['extra']),
]

Image

Thanks!

Metadata

Metadata

Assignees

Projects

Status

No status

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions