当前位置: 首页 > 后端技术 > PHP

laravel输出sql

时间:2023-03-29 19:01:16 PHP

第一步:打开Providers/AppServiceProvider.php,新方法sql_listen()/***监听数据库并转储sql,仅用于调试*@parambool|false$isShowTime*/functionsql_listen($isShowTime=false){app('db')->listen(function($queryExecuted,$bindings=[],$time='')使用($isShowTime){static$_static_sql=[];$sql='';if(is_object($queryExecuted)){$sql=$queryExecuted->sql;$bindings=$queryExecuted->bindings;$time=$queryExecuted->time;}foreach($bindingsas$i=>$binding){if(is_string($binding)){$bindings[$i]="'$binding'";}}$rawSql=str_replace(array('%','?'),array('%%','%s'),$sql);$rawSql=vsprintf($rawSql,$bindings).';';如果(!$_static_sql||!in_array($rawSql,$_static_sql)){$_static_sql[]=$rawSql;}else{返回;}$usedTime='';如果($isShowTime){$time=$time/1000;$usedTime="({$time}s)";}$sqlContent=$rawSql。$使用时间;logger()->channel('sqlLog')->info("我是SQL:".$sqlContent.PHP_EOL,[//'raw_sql'=>$sql,'connection_name'=>isset($queryExecuted->connectionName)?$queryExecuted->connectionName:'','duration_time'=>round($time,5),'created_at'=>date('Y-m-dH:i:s')]);});}然后boot方法注册sql_listen()函数/***Bootstrapanyapplicationservices.**@returnvoid*/publicfunctionboot(){$this->sql_listen(true);//调试sql监控或者检查慢sqlSchema::defaultStringLength(191);//添加固定的sql}第二步:在config/logging.phpchannels中添加sqlLog数组'sqlLog'=>['driver'=>'daily','name'=>'sqlmonitor','path'=>storage_path('logs/sql.log'),'level'=>'debug','days'=>15,'permission'=>0664,],step3:clearthecachestep4:To对一个数据库执行一个操作,然后回来查看是否有log日志目录:项目目录/storage/logs/tail-fsql-2021-04-23.log开心调试