Laravel 8 – Listen to eloquent events made during a specific request

Published

Currently, I’m trying to wire a telemetry library (OpenTelemetry php lib) to the Laravel event model. The idea is to forward traces to a third party service. A single trace consistents of a request and all database calls that have been made during the request. I’ve created three middleware components:

  • BeforeRequest: starts a trace
  • OnRequest: call event listener which listened to DB queries (see snippet below) and end trace so that it is send to a third party service

My OnRequest middleware component looks like this:

<?php

namespace AppHttpMiddleware;

use AppHelpersOtelTraceProviderFactory;
use Closure;
use IlluminateDatabaseEventsQueryExecuted;
use IlluminateHttpRequest;
use IlluminateSupportFacadesDB;

class OnRequest
{
     public function handle(Request $request, Closure $next)
     {
         $provider = TraceProviderFactory::getTraceProvider($request->get('context_uuid'));
         DB::listen(function (QueryExecuted $query) use ($provider){
              $provider->startDbSpan($query);
         });
         $provider->endSpans();

         return $next($request);
    }
}

In this case, the DB listen call is skipped over because it is async. How can I make sure that each database query is registered? The execution order is important. Everything needs to be in the right order otherwise the traces aren’t logged properly.

Source: Laravel

Published
Categorised as eloquent, laravel, laravel-8, php Tagged , , ,

Answers

Leave a Reply

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq