How to save my queries (sql strings) to the log file in Codeigniter?

1

My problem is as follows, how to register the queries (the generated sql string) in my log file. I know there is a function for this, but I do not want to have to call this guy in all my methods in my Model.

My question is, how could I solve this problem in a simpler way?

I thought of the hooks, but from what I could see I could not create a hook to access a Model.

    
asked by anonymous 02.06.2016 / 16:45

1 answer

2

To save a Log of all SQL (with established test it brings the SELECT only).

What would it be like:

Go to your configuration file application/config/config.php and the key enable_hooks put $config['enable_hooks'] = TRUE ;

Also within application/config in file hooks.php put the following 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 create a file in application/hooks with the name of db_log.php with the following code:

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

Ready, shortly after the first run, a log > file will be generated by date, inside the application/logs folder, storing all its SQL .

Website copyright and reference: JIGAR JAIN - Logging / Saving all DB queries in Codeigniter

There is also bitbucket for this settings: Codeigniter - Log all DB Queries in Log File , if you want to clone the repository.

    
02.06.2016 / 17:34