編輯config/web.php
首先log要開啟
'bootstrap' => [ 'log' ],
[file]
'components' => [ 'log' => [ 'targets' => [ [ 'class' => 'yii\log\FileTarget', 'exportInterval' => 1, ], ], ],
默認輸出到runtime/logs/app.log
注意webserver或控制台用戶要有寫入該文件的權限
[database]
'log' => [ 'targets' => [ [ 'class' => 'yii\log\DbTarget', 'levels' => ['error', 'warning', 'trace'], ] ] ],
默認輸出db組件對應的數據庫下{{%log}}表
yii2根目錄下運行下面命令生成對應的table schema
./yii migrate --migrationPath=@yii/log/migrations/
注意config/console.php下也要有和web.php同樣的配置,否則命令執行不成功。
還可以根據不同的環境配置不同的日志模式
'components' => [ 'log' => [ 'traceLevel' => YII_ENV == 'dev' ? 3 : 0, 'targets' => [ [ 'class' => 'yii\log\DbTarget', 'levels' => YII_DEBUG ? ['error', 'warning', 'trace'] : ['error'], ], [ 'class' => 'yii\log\FileTarget', 'levels' => YII_DEBUG ? ['error', 'warning', 'trace'] : ['error', 'warning'], ], ], ], ],