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

Asked

Viewed 519 times

1

My problem is the following, how to register queries(the generated sql string) in my log file. I know there’s a function to it, only I don’t want to have to call this guy in all my Model methods.

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

I thought about the Hooks, but from what I could see I couldn’t create a hook to access a Model.

1 answer

2

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

How would it be:

Goes in your configuration file application/config/config.php and the key enable_hooks place $config['enable_hooks'] = TRUE;

Also within application/config in the archive 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 by 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, soon after the first execution will be generated a file of log by date, inside the folder application/logs storing all of its SQL.

Reference and copyright to the website: JIGAR JAIN - Logging/Saving all DB queries in Codeigniter

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

  • I like this implementation. But funny that the attribute 'queries' is returning an empty array.

  • So I also implemented @Mathdesigner47 and it worked and first. Your log is enabled like this $config['log_threshold'] = 4; in the config.php file?

  • It is. But the whole thing is that this guy '$CI->db->queries' is empty. ?

  • "codeigniter/framework": "^3.0" that’s the version.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.