NEW Add new execmetric debug URL parameter to print out exection time and peak memory usage

This commit is contained in:
Maxime Rainville 2019-01-29 17:28:16 +13:00
parent 1b63610c27
commit c4bf06f600
3 changed files with 77 additions and 1 deletions

View File

@ -8,8 +8,16 @@ SilverStripe\Core\Manifest\VersionProvider:
Name: httpconfig-dev
Only:
environment: dev
After:
- 'requestprocessors'
---
# Set dev level to disabled with a higher forcing level
SilverStripe\Control\Middleware\HTTPCacheControlMiddleware:
defaultState: 'disabled'
defaultForcingLevel: 3
SilverStripe\Core\Injector\Injector:
SilverStripe\Control\Director:
properties:
Middlewares:
ExecMetricMiddleware: '%$SilverStripe\Control\Middleware\ExecMetricMiddleware'

View File

@ -29,6 +29,7 @@ session variables, used templates and much more.
| isTest | | 1 | | See above. |
| debug | | 1 | | Show a collection of debugging information about the director / controller operation |
| debug_request | | 1 | | Show all steps of the request from initial [HTTPRequest](api:SilverStripe\Control\HTTPRequest) to [Controller](api:SilverStripe\Control\Controller) to Template Rendering |
| execmetric | | 1 | | Display the execution time and peak memory usage for the request |
## Classes and Objects

View File

@ -0,0 +1,67 @@
<?php
namespace SilverStripe\Control\Middleware;
use SilverStripe\Assets\File;
use SilverStripe\Control\Director;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Dev\Debug;
/**
* Secures requests by only allowing a whitelist of Host values
*/
class ExecMetricMiddleware implements HTTPMiddleware
{
/**
* @inheritdoc
*/
public function process(HTTPRequest $request, callable $delegate)
{
if (!$this->showMetric($request)) {
return $delegate($request);
}
$start = microtime(true);
try {
return $delegate($request);
} finally {
$end = microtime(true);
Debug::message(
sprintf(
"Execution time: %s, Peak memory usage: %s\n",
$this->formatExecutionTime($start, $end),
$this->formatPeakMemoryUsage()
),
false
);
}
}
private function showMetric(HTTPRequest $request)
{
return Director::isDev() && array_key_exists('execmetric', $request->getVars());
}
/**
* Convert the provided start and end time to a interval in secs.
* @param float $start
* @param float $end
* @return string
*/
private function formatExecutionTime($start, $end)
{
$diff = round($end - $start, 4);
return $diff . ' seconds';
}
/**
* Get the peak memory usage formatted has a string and a meaningful unit.
* @return string
*/
private function formatPeakMemoryUsage()
{
$bytes = memory_get_peak_usage(true);
return File::format_size($bytes);
}
}