简体   繁体   中英

Add custom milestones to symfony profiler performance metrics

I would like to log the execution time of several code blocks in my application.

Is it possible to add custom data to the symfony profiler performance tab? (See image below)

Here's some pseudo code to illustrate what I want to achieve:

PerformanceProfiler::start('load foo data');

$data = $this->foo->load();

PerformanceProfiler::done('load foo data');

性能指标

This related question does not ask for a programmatic solution, so I decided to write a new question.

Use Symfony's Stopwatch component .

Unlike in their example, to get it to appear in the timeline, you have to inject a stopwatch as a service. So to use it in a controller, you'd do something like:

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Stopwatch\Stopwatch;

class MyController extends AbstractController
{
    public function someAction(Stopwatch $stopwatch): Response
    {
        // Giving it a category name will also give it
        // its own colour in the timeline, which is nice
        $stopwatch->start("My task's name", 'Optional category name');

        // Do the work you want to time

        $stopwatch->stop("My task's name");

        // Do anything else you want to do
    }
}

And of course you can inject it via the constructor in services etc.

I'm sure you're well past needing it now, but I came here looking for an answer and didn't find it, so hopefully this'll help someone else

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM