Magento 2 csvfile profiler – one request per file

Built-in functionality

Magento 2 provides built-in profilers to help developers to solve performance issues.

You can enabling the profiler just launching:

php bin/magento dev:profiler:enable <type>

This sets a semaphore file var/profiler.flag with the chosen profiler type. There are two out-of-the-box profilers:

  • html: this outputs a table with dependency graph in the bottom of each page;
  • csvfile: this outputs the dependency graph in var/log/profiler.csv file.

The profiler can track also methods interesting for your development using the functions:

public function myMethod()
{
	\Magento\Framework\Profiler::start('my-method');
	/*
		your code
	*/
	\Magento\Framework\Profiler::stop('my-method');
}

One request per file

Unfortunately csvfile profiler overrides always the same file, so if you do several requests only the last will be available at the end.

Searching in Magento\Framework\Profiler we find the class Magento\Framework\Profiler\Driver\Standard\Output\Csvfile responsable for the csv creation. Just putting a timestamp in the _parseFilePath function we obtain the desired result, but what if we have to deploy it in an environment where we can not edit vendor folder (like in most installations)?

Nevermind, you could think, let’s customize the csv filename, maybe with plugin on the method? Nope, the method is protected… Ok, what about extending the Csvfile class and overriding the method, then putting the new class as a preference in di.xml file of a custom module? Sounds good, let’s try it!

It seems not to work, how is it possible? Searching again in the code the profiler are instantiated with the new keyword, and this prevents the dependency injection mechanisms. Well, at this point you would like to break the keyboard, but the profiler must be efficient, so developers did the right thing.

So what can we do to output a csv for each request and deploy it without touch vendor folder?

We notice that in the Factory class for the output <type>, if type is a class it is instantiated, so it is sufficient to make a class that extends Csvfile with our modification and than launch it with:

php bin/magento dev:profiler:enable "\\Path\\To\\My\\Class"

I don’t know why but this simple information is missing in human language in the web, I only find it analysis the php code of Magento so I hope this will be useful for someone else.

I realize a module that just do this action of saving each request in a different csv file, and you can find it here:

https://github.com/zagonico86/magento2-module-customcsvprofiler