We already know how to log doctrine queries with symfony configuration files but If you want to programmatically do it, you can use example below.


Example


use Doctrine\ORM\EntityManagerInterface;
use Doctrine\DBAL\Logging\DebugStack;

class SearchService
{
private $entityManager;

public function __construct(
EntityManagerInterface $entityManager,
) {
$this->entityManager = $entityManager;
}

public function search(ProductSearch\Criteria $criteria)
{
$connection = $this->entityManager->getConnection();
$stack = new DebugStack();
$connection->getConfiguration()->setSQLLogger($stack);

// Do whatever you do here
// All the queries run here will be logged

file_put_contents('/var/www/html/your/app/logs/sql.log', json_encode($stack), FILE_APPEND);

return $result;
}
}

Log


{
"queries": {
"1": {
"sql": "SELECT name FROM orders WHERE id IS NOT NULL",
"params": [

],
"types": [

],
"executionMS": 0.00089383125305176
},
"2": {
"sql": "SELECT name, surname FROM user WHERE id = ?",
"params": [
"35ee78ea"
],
"types": [
"string"
],
"executionMS": 8.6069107055664e-5
},
"3": {
"sql": "SELECT total FROM purchases WHERE order_id = ?",
"params": [
6
],
"types": [
"integer"
],
"executionMS": 7.8916549682617e-5
}
},
"enabled": true,
"start": 1487860757.9865,
"currentQuery": 3
}