Example of SQL Logging Function Implemented by Laravel Framework

  • 2021-10-24 19:13:15
  • OfStack

In this paper, an example is given to describe the function of recording SQL log realized by Laravel framework. Share it for your reference, as follows:

During project development or performance tuning, it is often necessary to view the execution of sql, but the Laravel log does not record the execution of sql by default. Fortunately, with relevant interfaces, we can easily think of SQl log function.

Add the following to $listen in App\ Providers\ EventServiceProvider: class


protected $listen = [
  'App\Events\Event' => [
    'App\Listeners\EventListener',
  ],
  //  Add SqlListener Eavesdropping QueryExecuted
  'Illuminate\Database\Events\QueryExecuted' => [
    'App\Listeners\SqlListener',
  ],
];

New SqlListener Listener

Method 1, manually created in App\ Listeners\ SqlListener. php file, 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) {
    //  Write business logic here 
  }
}

Method 2, use the command line to create, the command is as follows


//  This command must be executed under projects and directories, because only under projects and directories artisan Files. 
//  This command can be automatically created SqlListener File, but QueryExecuted There may be some problems with the import of this class, so change it yourself. 

> php artisan make:listener SqlListener -e=QueryExecuted

Write business logic to record 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);
  //  You can also use it directly here Log::info()  The function in, but it will be mixed with other debugging information 1 Get up. 
  //  If you want to use Log Don't forget to introduce the functions in Log Class. 
}

For more readers interested in Laravel related content, please check the topics on this site: "Introduction and Advanced Tutorial of Laravel Framework", "Summary of Excellent Development Framework of php", "Introduction Tutorial of php Object-Oriented Programming", "Introduction Tutorial of php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

I hope this article is helpful to the PHP programming based on Laravel framework.


Related articles: