一聚教程网:一个值得你收藏的教程网站

热门教程

Laravel框架实现利用监听器进行sql语句记录功能

时间:2022-06-24 17:40:54 编辑:袖梨 来源:一聚教程网

本文实例讲述了Laravel框架实现利用监听器进行sql语句记录功能。分享给大家供大家参考,具体如下:

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

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

# 监听sql
make:listener QueryListener --event=IlluminateDatabaseEventsQueryExecuted

2、监听器类代码

./app/Listeners/QueryListener.php

sql);
    $log = vsprintf($sql, $event->bindings);
    # 此处$uid定义是依赖于中间件记录操作日志代码
    $uid = isset($_SERVER['admin_uid']) ? $_SERVER['admin_uid'] : 0;
    if('select' != substr($log , 0 , 6)){
      if('insert into `operationLog`' != substr($log , 0 , 26)){
        $OperationLog = new OperationLog();
        $OperationLog->uid = $uid;
        $OperationLog->sql = $log;
        $OperationLog->input = '';
        $OperationLog->save();
      }
    }
  }
}

3、引入监听器

./app/Providers/EventServiceProvider.php

protected $listen = [
    ...
    IlluminateDatabaseEventsQueryExecuted::class => [
      'AppListenersQueryListener'
    ],
    ...
  ];

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

热门栏目