This article mainly introduced the Laravel framework realizes the logging function, combined with the example form summarizes and analyzes the Laravel frame listens and records the SQL related operation skill and the attention matter, needs the friend can refer to the next
This article describes the logging SQL log functionality implemented by the LARAVEL framework. Share to everyone for your reference, as follows:
In a project development process or performance optimization, there are often cases where you want to see the execution of SQL, whereas the Laravel log does not record execution SQL by default. Fortunately, there are related interfaces, we can be very convenient is to think of SQL log function.
In the $listen in app\providers\eventserviceprovider:class , add the following
protected $listen = [ ' app\events\event ' = [ ' App\listeners\eventlistener ', ], // Added Sqllistener monitor queryexecuted ' illuminate\database\events\queryexecuted ' = [ ' app\listeners\ Sqllistener ', ],];
New Sqllistener Listener
Method 1, manually created, in the app\listeners\sqllistener.php file, the content is as follows
Namespace App\listeners;use illuminate\database\events\queryexecuted;class Sqllistener { /** * Create the Event listener. * * @return void * /Public Function __construct () { // } /** * Handle the event. * * @param =queryexecuted $event * @return void * /Public Function handle (queryexecuted $event) { c15/>//Write business logic here }}
Method 2, use the command line to create the command as follows
The command must be executed under the project and directory, because the project and directory have artisan files. This command can automatically create the Sqllistener file, but the import of this class queryexecuted may be a bit problematic for you to change. > PHP artisan make:listener sqllistener-e=queryexecuted
Write the business logic that records SQL in the handle method, such as:
/** * Handle the event. * * @param =queryexecuted $event * @return void */public function handle (queryexecuted $event) { $sql = Str_replace ("? "," '%s ' ", $event->sql); $log = vsprintf ($sql, $event->bindings); $log = ' ['. Date (' y-m-d h:i:s '). '] ' . $log. "\ r \ n"; $filepath = Storage_path (' Logs\sql.log '); File_put_contents ($filepath, $log, file_append); It is also possible to use the function in Log::info () directly, except that it will be mixed with other debugging information. //If you want to use the function in log, don't forget to introduce the log class. }
The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!