且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Zend 启用 SQL 查询日志记录

更新时间:2023-02-05 16:22:08

有一个扩展 Zend_Db_Profiler 的示例,以便您可以将查询写入/logs/db-queries.log 文件.

There is an example of extending Zend_Db_Profiler so you can write the queries to /logs/db-queries.log file.

所以你必须做到以下几点:

So you have to do the following:

  1. 在库文件夹中创建 My_Db_Profiler_Log 类
  2. 将以下行添加到 application.ini 中

resources.db.params.profiler.enabled = true

resources.db.params.profiler.enabled = true

resources.db.params.profiler.class = My_Db_Profiler_Log

resources.db.params.profiler.class = My_Db_Profiler_Log

注意:请注意,日志文件很快就会变得非常大!因此,只记录您感兴趣的查询是个好主意.本示例仅应被视为实现此类日志记录系统的起点.

Note: be aware, that the log file will become very big, very soon! So it is a good idea to log only the queries you are interested in. And this example should be considered only as a starting point in implementation of such a logging system.

这是自定义分析器类的代码:

Here is the code for the custom profiler class:

<?php

class My_Db_Profiler_Log extends Zend_Db_Profiler {

/**
 * Zend_Log instance
 * @var Zend_Log
 */
protected $_log;

/**
 * counter of the total elapsed time
 * @var double 
 */
protected $_totalElapsedTime;


public function __construct($enabled = false) {
    parent::__construct($enabled);

    $this->_log = new Zend_Log();
    $writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/logs/db-queries.log');
    $this->_log->addWriter($writer);
}

/**
 * Intercept the query end and log the profiling data.
 *
 * @param  integer $queryId
 * @throws Zend_Db_Profiler_Exception
 * @return void
 */
public function queryEnd($queryId) {
    $state = parent::queryEnd($queryId);

    if (!$this->getEnabled() || $state == self::IGNORED) {
        return;
    }

    // get profile of the current query
    $profile = $this->getQueryProfile($queryId);



        // update totalElapsedTime counter
        $this->_totalElapsedTime += $profile->getElapsedSecs();

        // create the message to be logged
        $message = "\r\nElapsed Secs: " . round($profile->getElapsedSecs(), 5) . "\r\n";
        $message .= "Query: " . $profile->getQuery() . "\r\n";

        // log the message as INFO message
        $this->_log->info($message);

}

}

?>