This article mainly introduces the Laravel framework realizes the function of SQL statement recording with listener, analyzes the creation and introduction of Laravel framework listener and the related operation skill of using listener to record SQL statement, and the Friends can refer to the following
The example in this paper describes the Laravel framework implementation of SQL statement recording function using listeners. Share to everyone for your reference, as follows:
Using listeners to record SQL statements
1. The event class that listens for SQL statements is already defined, and the listener class can be created directly:
# Monitor Sqlmake:listener Querylistener--event=illuminate\database\events\queryexecuted
2. Listener Class Code
./app/listeners/querylistener.php
<?phpnamespace app\listeners;use illuminate\database\events\ Queryexecuted;use Illuminate\queue\interactswithqueue;use Illuminate\contracts\queue\shouldqueue;use App\Http\ Models\operationlog;class querylistener{/** * Create the event listener. * * @return void */Public function __construct () {//}/** * Handle the event. * * @param queryexecuted $event * @return void */Public function handle (queryexecuted $event) {$sql = Str_rep Lace ("?", "'%s '", $event->sql); $log = vsprintf ($sql, $event->bindings); # Here the $UID definition is dependent on the middleware logging operation log Code $uid = isset ($_server[' Admin_uid ')? $_server[' Admin_uid ': 0; if (' select '! = substr ($log, 0, 6)) {if (' insert INTO ' operationlog '! = substr ($log, 0,)) {$OperationLog = new Operationlog (); $OperationLog->uid = $uid; $OperationLog->sql = $log; $OperationLog->input = "; $OperationLog->save (); } } }}
3. Introduction of Listeners
./app/providers/eventserviceprovider.php
protected $listen = [ ... \illuminate\database\events\queryexecuted::class = [ ' App\listeners\querylistener ' ], ... ];
The SQL log is logged when you do this