Skip to content

Instantly share code, notes, and snippets.

@dermanov-ru
Created November 4, 2020 12:29
Show Gist options
  • Save dermanov-ru/c23aa2541f7c9b71fc3e3c1216fb08f7 to your computer and use it in GitHub Desktop.
Save dermanov-ru/c23aa2541f7c9b71fc3e3c1216fb08f7 to your computer and use it in GitHub Desktop.
NewRelic APM Transactions name + Laravel
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Illuminate\Support\Str;
class NewRelicMiddleware
{
/**
* Handles the request by naming the transaction for New Relic
*
* @param Request $request
* @param Closure $next
*
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
// We must let the response get handled before naming the transaction, otherwise the necessary route i
// information won't be available in the request object.
$response = $next($request);
if (extension_loaded('newrelic')) {
newrelic_name_transaction($this->getTransactionName($request));
}
return $response;
}
/**
* Example "GET|HEAD api/v1/user"
*
* @param Request $request
* @return string
*/
public function getTransactionName(Request $request): string
{
$route = $request->route();
$transactionName = '';
if ($route instanceof Route) {
$transactionName = Str::replaceFirst('App\\Http\\Controllers\\', '', $route->getActionName());
}
return $transactionName;
}
}
@AlejandroKinoo
Copy link

Looks Great, but I keep getting Null on $request->route();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment