1、创建监听器
php artisan make:listener QueryListener
修改 handle
方法
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\Log;
...
public function handle(QueryExecuted $event)
{
// 只在测试环境下输出 log 日志
if (!app()->environment(['testing', 'local'])) {
return;
}
$sql = $event->sql;
$bindings = $event->bindings;
$time = $event->time; // 毫秒
$bindings = array_map(function ($binding) {
if (is_string($binding)) {
return (string)$binding;
}
if ($binding instanceof \DateTime) {
return $binding->format("'Y-m-d H:i:s'");
}
return $binding;
}, $bindings);
$sql = str_replace('?', '%s', $sql);
$sql = sprintf($sql, ...$bindings);
Log::info('sql_log', ['sql' => $sql, 'time' => $time . 'ms']);
}
2、注册监听事件
在系统的服务提供者 App\Providers\EventServiceProvider
中注册监听事件
protected $listen = [
...
QueryExecuted::class => [
QueryListener::class,
],
];
3、执行 sql 查看日志
可以在日志文件中看到 sql 的执行时间、sql 语句、毫秒数
[2022-05-08 22:45:04] local.INFO: sql_log {"sql":"select * from `user` where `user`.`id` = 3 limit 1","time":"51.59ms"}