yii2

How to get the sql of CreateCommand in Connection


Yii::$app->db->createCommand($sql)->queryAll(); How to get $sql Need to record all sql in createCommand It has been used in many places. How to record which sql is executed for each request with less intrusive code?

I thought about using behavior and event, but didn't figure it out


Solution

  • The implementation of yii\db\Command already supports query logging and profiling. It uses yii\log\Logger::LEVEL_INFO for logging and yii\log\Logger::LEVEL_PROFILE for profilling. Whether queries are logged or profiled is controlled by properties yii\db\Connection::$enableLogging and yii\db\Connection::$enableProfiling. Both are set to true by default.

    The logging/profiling uses yii\db\Command::query category for all query methods and yii\db\Command::execute category for execute() method.

    If you want to collect queries you can set up specific log target for them in your log dispatcher config for example like this:

    'components' => [
        'log' => [
            'targets' => [
                [
                    'class' => yii\log\FileTarget::class,
                    'logFile' => '@runtime/logs/sql.log',
                    'levels' => ['info'],
                    'enabled' => true,
                    'categories' => [
                        'yii\db\Command::query',
                        'yii\db\Command::execute'
                     ],
                    'logVars' => [],
                ],
                // ... other targets
            ],
        ],
        // ... other components config
    ],
    

    If existing log target classes are not enough for you can extend yii\log\Target to implement your own target and use it for collecting query log messages.

    PS. If you need to collect queries for debugging purpose the yiisoft/yii2-debug extension already implements query collecting and there is tab with queries and their info in its debug toolbar.