This article mainly and everyone introduced about Laravel to the production environment to add monitoring events (SQL log monitoring) related information, the article introduced in very detailed, for everyone has a certain reference learning value, hope to help everyone.
Laravel version: 5.2.*
First, create a listener
PHP Artisan Make:listener Querylistener--event=illuminate\\database\\events\\queryexecuted
Or
sudo/usr/local/bin/php Artisan Make:listener Querylistener--event=illuminate\\database\\events\\queryexecuted
Files are automatically generated app/listeners/querylistener.php
II. Registration of events
When you open app/providers/eventserviceprovider.php, the listener for the Add illuminate\database\events\queryexecuted event in the $listen is Querylistener
protected $listen = [ ' illuminate\database\events\queryexecuted ' = [ ' App\listeners\querylistener ',],];
The final code is as follows
Namespace App\providers;use Illuminate\contracts\events\dispatcher as Dispatchercontract;use Illuminate\Foundation\ Support\providers\eventserviceprovider as Serviceprovider;class Eventserviceprovider extends ServiceProvider{/** * The event listener mappings for the application. * * @var array */ protected $listen = [ ' app\events\someevent ' = [ ' App\listeners\eventlistener ', c6/>], ' illuminate\database\events\queryexecuted ' = [ ' App\listeners\querylistener ', ];/** * Register any and events for your application. * * @param \illuminate\contracts\events\dispatcher $events * @return void * /Public Function boot ( Dispatchercontract $events) { parent::boot ($events); // }}
Third, add logic
Open app/listeners/querylistener.php
The light has an empty listener is not enough, we need to implement how to log $sql. To this end, the Querylistener is reformed to improve its handle method as follows:
$sql = Str_replace ("?", "'%s '", $event->sql); $log = vsprintf ($sql, $event->bindings); Log::info ($log);
The final code is as follows
namespace App\listeners;use log;use Illuminate\database\events\queryexecuted;use illuminate\queue\ Interactswithqueue;use illuminate\contracts\queue\shouldqueue;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 = s Tr_replace ("?", "'%s '", $event->sql); $log = vsprintf ($sql, $event->bindings); Log::info ($log); }}