// web/index.php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', 3);
// config/main.php
'components' => [
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['trace'],
'categories' => ['yii\db\*'], // 關鍵:只記錄 DB 相關
'logFile' => '@runtime/logs/db.log',
'logVars' => [], // 不記錄 $_GET/$_SESSION 等,減小體積
],
// 保留原有應用日誌...
],
],
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=test',
'username' => 'root',
'password' => '',
'charset' => 'utf8mb4',
'enableSchemaCache' => true,
'schemaCacheDuration' => 3600,
'schemaCache' => 'cache',
],
],
2024-05-15 10:30:51.123 [trace] [yii\db\Command::query] Querying SQL: SELECT * FROM `user` WHERE `id`=1
2024-05-15 10:30:51.124 [trace] [yii\db\Command::execute] Executing SQL: INSERT INTO `log` (`message`) VALUES ('login')
2024-05-15 10:30:51.125 [profile] [yii\db\Command::query] Querying SQL: SELECT * FROM `user` WHERE `id`=1 (0.000456s)
[trace]:SQL 文本與綁定參數。[profile]:含執行耗時,啟用 enableProfiling 後產生。categories 設為 yii\db\* 可捕獲 Command、Connection、 等所有 DB 追蹤。// composer require --dev yiisoft/yii2-debug
// config/main-local.php (開發環境)
if (YII_DEBUG) {
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
'allowedIPs' => ['127.0.0.1', '::1', '192.168.*.*'],
];
}
訪問 /debug 即可查看每請求的 SQL 執行時間、EXPLAIN 分析、重複查詢檢測等。
YII_DEBUG,traceLevel = 0。640,目錄 750,屬主 www-data:www-data。logrotate 配置 /var/www/app/runtime/logs/db.log daily rotate 14。yii\db\Command::queryInternal 過濾。