【问题标题】:CakePHP 2: Get full SQL error log in error.logCakePHP 2:在 error.log 中获取完整的 SQL 错误日志
【发布时间】:2013-01-29 13:23:31
【问题描述】:

我希望能够在 error.log 中记录完整的 SQL 查询,特别是在发生 SQL 错误时。我的调试在 core.php 中设置为 2。

输出如下:

2013-01-29 19:53:21 Error: SQLSTATE[HY000]: General error: 1364 Field 'street' doesn't have a default value
#0 D:\xampp\htdocs\my_project\lib\Cake\Model\Datasource\DboSource.php(459): PDOStatement->execute(Array)
#1 D:\xampp\htdocs\my_project\lib\Cake\Model\Datasource\DboSource.php(425): DboSource->_execute('INSERT INTO `st...', Array)
#2 D:\xampp\htdocs\my_project\lib\Cake\Model\Datasource\DboSource.php(1007): DboSource->execute('INSERT INTO `st...')

如您所见,SQL 语句只记录了部分,其余部分被省略了。

我将 DebugKit 与此结合使用,但即使这样也不会在 DebugKit 窗口中生成完整的 SQL 日志。

我在这里抛出异常并记录 getTraceAsString()。

任何解决方案将不胜感激。

谢谢你,
m^e

【问题讨论】:

    标签: sql cakephp logging logfile


    【解决方案1】:

    您可以尝试使用this question的答案。我知道这不是最佳答案,但在那个特定问题中,您可以找到this plugin,它将输出日志文件的完整 SQL。

    【讨论】:

      【解决方案2】:

      我做了以下(Cake 2.5.6)

      1. 中创建自定义错误处理程序

      /app/Lib/Error/ErrorHandlerWithSqlLog.php

      App::uses('ErrorHandler', 'Error');
      class ErrorHandlerWithSqlLog{
          public static function handleException(Exception $exception) {
              if ($exception instanceof PDOException && !empty($exception->queryString)) {            
                  CakeLog::write(LOG_ERR, "SQL query: ".$exception->queryString);
              }        
              ErrorHandler::handleException($exception);      
          }
      }
      

      将其添加到您的引导程序中:

      require_once(APP . 'Lib' . DS . 'Error' . DS . 'ErrorHandlerWithSqlLog.php');
      

      并将 core.php 中的默认异常处理程序更改为自定义处理程序:

      Configure::write('Exception', array(
          //'handler' => 'ErrorHandler::handleException',
          'handler' => 'ErrorHandlerWithSqlLog::handleException',
          'renderer' => 'ExceptionRenderer',
          'log' => true
      ));
      

      【讨论】:

        【解决方案3】:

        捕捉异常更容易,

        PDOException 在当前查询中有一个名为 queryString 的属性

        你可以在_execute Method中的源文件DboSource.php中看到

        try {
        $this->MyModel->find(....)
        }catch(Exception $_ex) {
        var_dump($_ex)
        }
        

        希望对你有帮助

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多