|
|
|
1
|
+<?php
|
|
|
|
2
|
+
|
|
|
|
3
|
+namespace App\Listeners;
|
|
|
|
4
|
+
|
|
|
|
5
|
+use Illuminate\Contracts\Queue\ShouldQueue;
|
|
|
|
6
|
+use Illuminate\Database\Events\QueryExecuted;
|
|
|
|
7
|
+use Illuminate\Queue\InteractsWithQueue;
|
|
|
|
8
|
+use Illuminate\Support\Facades\Log;
|
|
|
|
9
|
+use Illuminate\Support\Facades\Redis;
|
|
|
|
10
|
+
|
|
|
|
11
|
+/**
|
|
|
|
12
|
+ * 监听数据库sql执行事件
|
|
|
|
13
|
+ */
|
|
|
|
14
|
+class QueryListener
|
|
|
|
15
|
+{
|
|
|
|
16
|
+ /**
|
|
|
|
17
|
+ * Create the event listener.
|
|
|
|
18
|
+ *
|
|
|
|
19
|
+ * @return void
|
|
|
|
20
|
+ */
|
|
|
|
21
|
+ public function __construct()
|
|
|
|
22
|
+ {
|
|
|
|
23
|
+ //
|
|
|
|
24
|
+ }
|
|
|
|
25
|
+
|
|
|
|
26
|
+ /**
|
|
|
|
27
|
+ * Handle the event.
|
|
|
|
28
|
+ *
|
|
|
|
29
|
+ * @param QueryExecuted $event
|
|
|
|
30
|
+ * @return void
|
|
|
|
31
|
+ */
|
|
|
|
32
|
+ public function handle(QueryExecuted $event)
|
|
|
|
33
|
+ {
|
|
|
|
34
|
+ try{
|
|
|
|
35
|
+ if (env('APP_DEBUG') == true) {
|
|
|
|
36
|
+ $sql = str_replace("?", "'%s'", $event->sql);
|
|
|
|
37
|
+ foreach ($event->bindings as $i => $binding) {
|
|
|
|
38
|
+ if ($binding instanceof \DateTime) {
|
|
|
|
39
|
+ $event->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
|
|
|
|
40
|
+ } else {
|
|
|
|
41
|
+ if (is_string($binding)) {
|
|
|
|
42
|
+ $event->bindings[$i] = "$binding";
|
|
|
|
43
|
+ }
|
|
|
|
44
|
+ }
|
|
|
|
45
|
+ }
|
|
|
|
46
|
+ $log = vsprintf($sql, $event->bindings);
|
|
|
|
47
|
+ $log = $log.' [ RunTime:'.$event->time.'ms ] ';
|
|
|
|
48
|
+ Log::debug($log);
|
|
|
|
49
|
+ }
|
|
|
|
50
|
+ }catch (\Exception $exception){
|
|
|
|
51
|
+ Log::error('log sql error:'.$exception->getMessage());
|
|
|
|
52
|
+ }
|
|
|
|
53
|
+ }
|
|
|
|
54
|
+} |