Skip to content

Introduce trace helper function#1490

Merged
stayallive merged 3 commits intomasterfrom
trace-helper
Mar 14, 2023
Merged

Introduce trace helper function#1490
stayallive merged 3 commits intomasterfrom
trace-helper

Conversation

@stayallive
Copy link
Collaborator

This adds the trace helper function that reduces a lot of boilerplate of adding spans for user code, allowing users to quickly wrap existing calls with a span and it looks something like this:

use Sentry\State\Scope;
use Sentry\Tracing\SpanContext;
use function Sentry\trace;

$args = [...];

$result = trace(
    function (Scope $scope) use ($args) {
        $scope->setTag('some-tag', 'some-value');

        return $this->doSomethingThatNeedsToBeTraced($args);
    },
    tap(new SpanContext, function (SpanContext $context) use ($args) {
        $context->setOp('something.measurable');
        $context->setData(['context' => $args]);
        $context->setDescription('Something measurable');
    }),
);

The SpanContext is a unfortunate object in our API at the moment and doesn't have a fluent interface so I've used the tap() helper from Laravel to keep it a little more readable in the example.

This was originally coined in Laravel (getsentry/sentry-laravel#598) but is general enough for all of PHP to benefit from.

@cleptric
Copy link
Member

cleptric commented Mar 14, 2023

$client = new Client();

$spanContext = new SpanContext();
$spanContext->setOp('http.client');
$spanContext->setDescription('GET http://google.com');

trace(
    function (Scope $scope) use ($client) {
        return $client->get('http://google.com');
    },
    $spanContext,
);
$spanContext = new SpanContext();
$spanContext->setOp('http.client');
$spanContext->setDescription('GET http://google.com');

$transaction = SentrySdk::getCurrentHub()->getTransaction();
$span = $transaction->startChild($spanContext);

$client = new Client();
$client->get('http://google.com');

$span->finish();

A small improvement, but it is an improvement!

@stayallive
Copy link
Collaborator Author

Yeah, the context thing is unfortunate. If it had a fluent syntax we could so some really cool things like:

trace(...)
    ->op('some.op')
    ->description('Something to trace')
    ->run()

Which honestly might be attainable actually... without breaking changes. Worth it?

@cleptric
Copy link
Member

Not sure tbh. We now have a way better span creator, called profiling 😛

I still think it's worth going this route in v4, but would be ok with the current approach for now.

@stayallive stayallive merged commit efe7331 into master Mar 14, 2023
@stayallive stayallive deleted the trace-helper branch March 14, 2023 20:25
@cleptric cleptric added this to the 3.16.0 milestone Mar 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants