Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP 2: Get full SQL error log in error.log

I want to be able to log full SQL queries in error.log specifically when a SQL error occurs. My debug is set to 2 in core.php.

The output is appearing as follows:

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...')

As you can see, the SQL statements are only logged partially with the rest being chopped-of with ellipsis.

I'm using DebugKit in conjunction with this, but even that doesn't produce full SQL logs at time in the DebugKit window.

I'm throwing exceptions and logging the getTraceAsString() here.

Any solutions will be greatly appreciated.

Thank you,
m^e

like image 676
miCRoSCoPiC_eaRthLinG Avatar asked May 15 '26 22:05

miCRoSCoPiC_eaRthLinG


1 Answers

I did the following (Cake 2.5.6)

  1. create custom error handler in

/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);      
    }
}

add it to your bootstrap:

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

and change yor default exception handler in core.php to the custom one:

Configure::write('Exception', array(
    //'handler' => 'ErrorHandler::handleException',
    'handler' => 'ErrorHandlerWithSqlLog::handleException',
    'renderer' => 'ExceptionRenderer',
    'log' => true
));
like image 186
Panter4 Avatar answered May 18 '26 16:05

Panter4



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!