1 添加一个日志通道 : 打开 config/logging.php
'sql'=>[
'driver' => 'daily',
'level' => 'debug',
'path' => storage_path('logs/sql/log.log'),
],
2 创建监听器
php artisan make:listener QueryListener --event=IlluminateDatabaseEventsQueryExecuted
打开 app/Providers/EventServiceProvider.php ,在 $listen 中添加
protected $listen = [
'IlluminateDatabaseEventsQueryExecuted' => [
'AppListenersQueryListener',
]
];
打开 app/Listeners/QueryListener 文件
//第一步:头部引入log
use IlluminateSupportFacadesLog;
//第二步:handle方法修改如下
public function handle(QueryExecuted $event)
{
if (env('APP_DEBUG') {
$sql = str_replace("?", "'%s'", $event->sql);
$log = vsprintf($sql, $event->bindings);
$logDir = storage_path('logs/sql');
if (!is_dir($logDir)) {
mkdir($logDir, 0777, true);
}
Log::channel('sql')->info($log);
}
}
运行代码。就可以在 storage/logs/sql 下 看到sql 日志了