php - ZF2 Zend\Log + Doctrine2

标签 php doctrine-orm zend-framework2 zend-log

我不知道如何使用 Doctrine2 配置 Zend\Log。只允许您通过连接适配器直接写入数据库或写入文件。

最佳答案

也许现在回答这个问题为时已晚,但迟到总比不到好。

我找到了一篇很好的文章,它解释了如何为 ZF2 和 Doctrine 创建一个基本的 SQL Logger

方法很简单:

<强>1。创建 Logger 类: 在 Module/Application/Log 文件夹中创建以下类:

    <?php
    namespace Application\Log;

    use Zend\Log\Logger;  
    use Doctrine\DBAL\Logging\DebugStack;

    class SqlLogger extends DebugStack  
    {
        protected $logger;
        
        public function __construct(Logger $logger)
        {
            $this->logger = $logger;
        }

        public function stopQuery()
        {
            parent::stopQuery();
            $q = $this->queries[$this->currentQuery];
            $message = "Executed Query:  " . print_r($q, true);
            $this->logger->info($message);
        }
    }

Doctrine 在完成向数据库服务器发送查询时调用的 stopQuery() 函数是 重写以便它可以将当前查询写入 Logger 对象。

<强>2。配置记录器: 在您的 config/autoload/global.php 文件中添加以下代码,使 Service Manager 使用名称 my_sql_logger 可访问的 Logger:

        'service_manager' => array(
            'factories' => array(
                'my_sql_logger' => function($sm) {
                    $log = new \Zend\Log\Logger();
                    $writer = new \Zend\Log\Writer\Stream('./data/logs/sql.log');
                    $log->addWriter($writer);

                    $sqllog = new \Application\Log\SqlLogger($log);
                    return $sqllog;
                },
            )
        ),
        

Logger 会将数据写入data/logs/sql.log 文件。因此,请确保 data/logs 文件夹存在于您的 应用程序根目录。

<强>3。配置 Doctrine : 现在你需要告诉 Doctrine 使用创建的 Logger。只需添加以下代码 到你的学说配置:

    return array(  
        'doctrine' => array(
             /*--------Add this code------------*/
            'sql_logger_collector' => array(
                'orm_default' => array(
                    'sql_logger' => 'my_sql_logger',
                ),
            ),
            /*---------------------------------*/
            'connection' => array(
                'orm_default' => array(
                    'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
                    'params' => array(
                        'host' => 'localhost',
                        'port' => '3306',
                        'user' => 'username',
                        'password' => 'password',
                        'dbname' => 'dbname',
                    ),
                ),
            ),
        ),
    );

通过上面配置的 Zend\LogDoctrine2,你会得到所有的查询数据记录在 data/log/sql.log 文件。

请看这个Sql Logger for ZF2 and Doctrine了解更多详情。

关于php - ZF2 Zend\Log + Doctrine2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20814510/

相关文章:

php - 简单AJAX提交并更新mysql

php - 在 Redbean 中将 IN 与其他条件一起使用

symfony - Doctrine 需要在 OneToMany 单向关联中使用mappedBy

php - 删除自引用的@ManyToMany 连接

php - 如何使用带有函数的php isset?

mysql - 我如何调用存储过程(使用 zf2,学说 2)?

mysql - Zend Framework 2 和 mysql 使用 ssh

php - 如何在 PHP 中获取文件扩展名?

php - 从 MySQL 表中获取详细信息,如长度、值

mysql - 我不能用 Doctrine 2 加入两张 table