Symfony2 在 Symfony 和 csv 文件中添加查询日志记录

Symfony2 add query logging in Symfony and in csv file

我需要在 Symfony 和 csv 文件中添加查询日志记录。有时数据库可能很忙或不可用,但我想记录所有查询。

此日志应为 csv 格式,包含以下列:

-url

-数据源名称

-SQL内容

-参数

-用户名

-查询执行开始时间(毫秒精度)

-查询执行结束时间(毫秒精度)

有什么帮助吗?或者可以为此做些什么?

也许是自定义函数,我可以在其中创建包含当前登录用户信息的 csv 文件以及 url 和执行查询以访问特定 url 的时间?

In Symfony If you have a common SQL function which runs when each query executes then this one helpful for you.

这是我在我的案例中实现的。希望这对你有帮助。

public function execute($parameters = null)
{
if ($this->executed) {
return $this;
}
$executionStartTime = microtime(true);

$stmt = $this->execute($parameters);
$this->result = $stmt->fetchAll();
// Close cursor to allow query caching.
$stmt->closeCursor();
$this->executed = true;;

$executionEndTime = microtime(true);

//below code is added to logging for SQL queries to web server in csv format
$execution_time = $executionEndTime - $executionStartTime;
$getpageParameter = $parameters;
$getusername = $this->getUser()->getUsername();
$url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

$parms = json_encode($getpageParameter);

$data = array(
date ("Y-m-d H:i:s")."|".$url."|".$getusername."|".$parms."|".$executionStartTime."|".$executionEndTime,
);

if(!file_exists('/../../app/logs/querylog.csv')){
$column = array(
"DATE & TIME|URL|USERNAME|PARAMETERS|START TIME|END TIME"
);
$fp = fopen('/../../app/logs/querylog.csv', 'a+');
foreach ( $column as $line ) {
$val = explode("|", $line);
fputcsv($fp, $val);
}
fclose($fp);
}

$fp = fopen('/../../app/logs/querylog.csv', 'a+');
foreach ( $data as $line ) {
$val = explode("|", $line);
fputcsv($fp, $val);
}
fclose($fp);

return $this;
}