16

i want to log all queries after execution using hooks. -i enabled hooks in config.php -this is my hook-->

 $hook['post_controller'] = array(    
    'class' => 'Db_log',             
    'function' => 'logQueries',     
   'filename' => 'db_log.php',    
   'filepath' => 'hooks'         
  );

-and this is hook defination-->

class Db_log 
{

    function __construct() 
    {
    }


    function logQueries() 
    {
        $CI = & get_instance();

        $filepath = APPPATH . 'logs/Query-log-' . date('Y-m-d') . '.php'; 
        $handle = fopen($filepath, "a+");                        

        $times = $CI->db->query_times;
        foreach ($CI->db->queries as $key => $query) 
        { 
            $sql = $query . " \n Execution Time:" . $times[$key]; 

            fwrite($handle, $sql . "\n\n");    
        }

        fclose($handle);  
    }

}

--its creating query_log file --but no records of queries being stored

2 Answers 2

14

Your Code looks fine - the only reason why this doesn't work is in your DB Configuration - take a look @your DB Connection in the database.php under application/config/

There is an option "save_queries" which should be set to true

$db['default'] = array(
    ...
    'save_queries' => TRUE
);
6
  • 2
    above code is now working fine...but its logging SELECT queries only,what if i want only INSERT,UPDATE and DELETE be logged instead of SELECT queries? Sep 28, 2016 at 6:20
  • even the other types of Queries should get logged - in the queries are all type of queries
    – Atural
    Sep 28, 2016 at 11:05
  • is there any option to "$CI->db->queries" Sep 29, 2016 at 10:43
  • what do you mean with option ? do you want to separate inserts, updates, delets and selects from each other ?
    – Atural
    Sep 29, 2016 at 11:06
  • 2
    internal redirection in application was causing it to overtake hook execution, that's why it wasn't logging modification statements...i found the solution thereafter. Oct 1, 2016 at 7:32
0

For me it only worked when I define de $hook array in config/hooks.php .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.