Laravel 4 - logging SQL queries

前端 未结 6 1708
时光取名叫无心
时光取名叫无心 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:33

    While the question was originally targeted at Laravel 4, I still ended up here through google, but I'm using Laravel 5.

    There are new ways to log all queries in Laravel 5 using Middleware, but if you prefer the same approach here is the same code provided by Collin James but working for Laravel 5

    if (Config::get('database.log', false))
    {
        Event::listen('Illuminate\Database\Events\QueryExecuted', function($query)
        {
            $bindings = $query->bindings;
            $time = $query->time;
            $name = $query->connection->getName();
            $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->sql);
            $query = vsprintf($query, $bindings);
    
            Log::info($query, $data);
        });
    }
    

提交回复
热议问题