Laravel 4 - logging SQL queries

前端 未结 6 1697
时光取名叫无心
时光取名叫无心 2020-11-28 04:40

There are already several questions in regards to logging the SQL query in Laravel 4. But I\'ve tried almost all of them and it\'s still not working the way I want.

6条回答
  •  离开以前
    2020-11-28 05:10

    Here is what I am currently using for logging of sql queries. You should be able to drop this into your main routes file then add 'log' => true into your database config.

    if (Config::get('database.log', false))
    {           
        Event::listen('illuminate.query', function($query, $bindings, $time, $name)
        {
            $data = compact('bindings', 'time', 'name');
    
            // Format binding data for sql insertion
            foreach ($bindings as $i => $binding)
            {   
                if ($binding instanceof \DateTime)
                {   
                    $bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
                }
                else if (is_string($binding))
                {   
                    $bindings[$i] = "'$binding'";
                }   
            }       
    
            // Insert bindings into query
            $query = str_replace(array('%', '?'), array('%%', '%s'), $query);
            $query = vsprintf($query, $bindings); 
    
            Log::info($query, $data);
        });
    }
    

    Thanks to Jeemusu answer for the bit about inserting the bindings into the prepared statement.

提交回复
热议问题