Skip to content

Instantly share code, notes, and snippets.

@hussainweb
Created November 23, 2016 05:20
Show Gist options
  • Save hussainweb/7daaac7f1c3b92613f5f7508dd2b6710 to your computer and use it in GitHub Desktop.
Save hussainweb/7daaac7f1c3b92613f5f7508dd2b6710 to your computer and use it in GitHub Desktop.
This Laravel middleware allows developers to profile specific requests by appending `xhprof=true` to any query.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use XHProfRuns_Default;
/**
* Class XhprofMiddleware.
*
* XHProf is a useful profiling tool built by Facebook. This middleware allows
* developers to profile specific requests by appending `xhprof=true` to any
* query.
*
* Results will be stored on `/tmp` and can be visualized using the XHProf UI.
*/
class XhprofMiddleware
{
/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
// We will only profile requests if the proper flag is set on the query
// of the request. You may further customize this to be disabled on
// production releases of your application.
if ($request->query->get('xhprof') !== 'true') {
return $next($request);
}
require_once '/usr/share/php/xhprof_lib/utils/xhprof_lib.php';
require_once '/usr/share/php/xhprof_lib/utils/xhprof_runs.php';
xhprof_enable();
$result = $next($request);
$xhprofData = xhprof_disable();
$xhprofRuns = new XHProfRuns_Default('/tmp');
$runId = $xhprofRuns->save_run($xhprofData, 'xhprof_laravel');
// We will attach the XHProf run ID as part of the response header.
// This is a lot better than modifying the actual response body.
$result->headers->set('X-Xhprof-Run-Id', $runId);
return $result;
}
}
@hussainweb
Copy link
Author

Add this middleware in your app/Html/Kernel.php in $middleware property.

class Kernel extends HttpKernel
{
    protected $middleware = [
        ...
        \App\Http\Middleware\XhprofMiddleware::class,
    ];
    ...
}

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