Create a log of your Database Queries that are getting executed while running a application written in Codeigniter

First of all enable the hooks from your config file . Just Open the config.php in you application/cofig folder $config['enable_hooks'] = TRUE; Now open the hooks.php and write down the code $hook['post_controller'] = array( // 'post_controller' indicated execution of hooks after controller is finished 'class' => 'Db_log', // Name of Class 'function' => 'logQueries', // Name of function to be executed in from Class 'filename' => 'db_log.php', // Name of the Hook file 'filepath' => 'hooks' // Name of folder where Hook file is stored ); Now we will create the hook with name db_log.php which we have set above and save it in application/hooks/ folder. Then we simply put the following code in this file. // Name of Class as mentioned in $hook['post_controller] class Db_log { function __construct() { // Anything except exit() :P } // Name of function same as mentioned in Hooks Config function logQueries() { $CI = & get_instance(); $filepath = APPPATH . 'logs/Query-log-' . date('Y-m-d') . '.php'; // Creating Query Log file with today's date in application/logs folder $handle = fopen($filepath, "a+"); // Opening file with pointer at the end of the file $times = $CI->db->query_times; // Get execution time of all the queries executed by controller foreach ($CI->db->queries as $key => $query) { $sql = $query . " \n Execution Time:" . $times[$key]; // Generating SQL file alongwith execution time fwrite($handle, $sql . "\n\n"); // Writing it in the log file } fclose($handle); // Close the file } } Now every time any of your controller gets executed, the DB queries if executed any will be logged in Query-log file in Logs folder. Do note that you need to give write access to your application/logs folder.

Comments

Popular posts from this blog

Enable the imap in support in xampp server