Laravel 框架记录 sql 日志
作者:互联网
Laravel 版本:Laravel Framework 5.8.31
Laravel 框架默认是不会记录 sql 日志的,需要手动添加。
1、在 app/Providers/EventServicePorvider.php 文件 $listen 中添加要注册的事件:
protected $listen = [ 'Illuminate\Database\Events\QueryExecuted' => [ 'App\Listeners\QueryListener', ], ];
2、生成事件 & 监听器,执行命令:
php artisan event:generate
3、在 App\Listeners\QueryListener 文件的 handle 方法中编写记录 sql 的业务逻辑:
public function handle(QueryExecuted $event) { try{ if (env('APP_DEBUG') == true) { $sql = str_replace("?", "'%s'", $event->sql); foreach ($event->bindings as $i => $binding) { if ($binding instanceof \DateTime) { $event->bindings[$i] = $binding->format('\'Y-m-d H:i:s\''); } else { if (is_string($binding)) { $event->bindings[$i] = "'$binding'"; } } } $log = vsprintf($sql, $event->bindings); $log = $log.' [ RunTime:'.$event->time.'ms ] '; (new Logger('sql'))->pushHandler(new RotatingFileHandler(storage_path('logs/sql/sql.log')))->info($log); } }catch (\Exception $exception){ Log::error('log sql error:'.$exception->getMessage()); } }
Enjoy it !
标签:Laravel,bindings,log,binding,sql,日志,event 来源: https://www.cnblogs.com/daizhongxing/p/12986205.html