QueryListener.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Listeners;
  3. use Illuminate\Database\Events\QueryExecuted;
  4. use Illuminate\Support\Facades\Log;
  5. use Monolog\Handler\RotatingFileHandler;
  6. use Monolog\Logger;
  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. try{
  27. if (env('APP_DEBUG') == true) {
  28. $this->recordLog($event, 'logs/sql/sql.log');
  29. }
  30. }catch (\Exception $exception){
  31. Log::error('log sql error:'.$exception->getMessage());
  32. }
  33. }
  34. protected function recordLog($event, $sqlFile)
  35. {
  36. $sql = str_replace("?", "'%s'", $event->sql);
  37. foreach ($event->bindings as $i => $binding) {
  38. if ($binding instanceof \DateTime) {
  39. $event->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
  40. } else {
  41. if (is_string($binding)) {
  42. $event->bindings[$i] = "'$binding'";
  43. }
  44. }
  45. }
  46. $log = vsprintf($sql, $event->bindings);
  47. $log = $log.' [ RunTime:'.$event->time.'ms ] ';
  48. (new Logger('sql'))->pushHandler(new RotatingFileHandler(storage_path($sqlFile)))->info($log);
  49. }
  50. }