利用监听器进行sql语句记录

1、监听sql语句的事件类已经定义,直接创建监听器类即可:

  1. # 监听sql
  2. make:listener QueryListener --event=Illuminate\Database\Events\QueryExecuted

2、监听器类代码

./app/Listeners/QueryListener.php

  1. <?php
  2. namespace App\Listeners;
  3. use Illuminate\Database\Events\QueryExecuted;
  4. use Illuminate\Queue\InteractsWithQueue;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. use App\Http\Models\OperationLog;
  7. class QueryListener
  8. {
  9. /**
  10. * Create the event listener.
  11. *
  12. * @return void
  13. */
  14. public function __construct()
  15. {
  16. //
  17. }
  18. /**
  19. * Handle the event.
  20. *
  21. * @param QueryExecuted $event
  22. * @return void
  23. */
  24. public function handle(QueryExecuted $event)
  25. {
  26. $sql = vsprintf(str_replace("?", "'%s'", $event->sql), $event->bindings) . " \t[" . $event->time . ' ms] ';
  27. Log::error($sql);
  28. }
  29. }

3、引入监听器

./app/Providers/EventServiceProvider.php

  1. protected $listen = [
  2. ...
  3. \Illuminate\Database\Events\QueryExecuted::class => [
  4. 'App\Listeners\QueryListener'
  5. ],
  6. ...
  7. ];

此时进行操作时就会记录sql日志

相关文章:

laravel 利用中间件进行操作日志记录

Lumen 框架sql监听

1、创建sql监听器

QueryListener.php

  1. <?php
  2. namespace App\Listeners;
  3. use App\Http\Helpers\FunctionHelper;
  4. use Illuminate\Database\Events\QueryExecuted;
  5. use Illuminate\Support\Facades\Log;
  6. class QueryListener
  7. {
  8. /**
  9. * Create the event listener.
  10. *
  11. * @return void
  12. */
  13. public function __construct()
  14. {
  15. //
  16. }
  17. /**
  18. * Handle the event.
  19. *
  20. * @param QueryExecuted $event
  21. * @return void
  22. */
  23. public function handle(QueryExecuted $event)
  24. {
  25. if (FunctionHelper::isTestEnv()) {
  26. Log::info($event->sql);
  27. Log::info($event->bindings);
  28. }
  29. }
  30. }

2、加入到监听服务中

EventServiceProvider.php

  1. <?php
  2. namespace App\Providers;
  3. use App\Listeners\QueryListener;
  4. use Illuminate\Database\Events\QueryExecuted;
  5. use Laravel\Lumen\Providers\EventServiceProvider as ServiceProvider;
  6. class EventServiceProvider extends ServiceProvider
  7. {
  8. /**
  9. * The event listener mappings for the application.
  10. *
  11. * @var array
  12. */
  13. protected $listen = [
  14. \App\Events\ExampleEvent::class => [
  15. \App\Listeners\ExampleListener::class,
  16. ],
  17. # 注册sql监听
  18. QueryExecuted::class => [
  19. QueryListener::class,
  20. ],
  21. ];
  22. }

3、项目入口引入监听服务

bootstrap/app.php

  1. $app->register(App\Providers\EventServiceProvider::class);