laravel 使用dingo api 添加sql调试
1、在appServiceProvider启动boot中添加
if(env("APP_DEBUG"))\DB::enableQueryLog();
2、在需要调试的地方直接使用:
dd(\DB::getQueryLog());
以下采用更加优雅的方式实现(配合debugbar):
前提:需要安装debugbar扩展
1、添加json返回处理的中间件 ProcessJsonResponse
1 namespace App\Http\Middleware; 2 use Closure; 3 use Dingo\Api\Http\Response; 4 5 class ProcessJsonResponse 6 { 7 /** 8 * Handle an incoming request. 9 * 10 * @param \Illuminate\Http\Request $request 11 * @param \Closure $next 12 * @return mixed 13 */ 14 public function handle($request, Closure $next) 15 { 16 $response = $next($request); 17 if ( 18 env("APP_DEBUG")&& 19 $request->ajax()&& 20 $response instanceof Response && 21 app()->bound('debugbar') && 22 app('debugbar')->isEnabled() 23 ) { 24 $debugbar_data=app('debugbar')->getData(); 25 $queries_data = $this->sqlFilter($debugbar_data); 26 $total_duration_time=array_get($debugbar_data, 'time.duration_str'); 27 $response->setContent(json_decode($response->morph()->getContent(), true) + [ 28 '_debugbar' => [ 29 'total_queries' => count($queries_data), 30 'total_duration_time'=>$total_duration_time, 31 'queries' => $queries_data, 32 ] 33 ]); 34 } 35 36 return $response; 37 } 38 39 /** 40 * Get only sql and each duration 41 * 42 * @param $debugbar_data 43 * @return array 44 */ 45 protected function sqlFilter($debugbar_data) { 46 $result = array_get($debugbar_data, 'queries.statements'); 47 48 return array_map(function ($item) { 49 return [ 50 'sql' => array_get($item, 'sql'), 51 'duration' => array_get($item, 'duration_str'), 52 ]; 53 }, $result); 54 } 55 }
2、修改配置文件api.php添加全局中间件控制(也可以参照laravel自行添加路由中间件)
1 'middleware' => [ 2 \App\Http\Middleware\ProcessJsonResponse::class,//dingo api 接口返回内容添加sql by winston 3 ],
效果: