首页 > 数据库 >laravel 利用监听器进行sql语句记录

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

时间:2023-03-23 12:32:40浏览次数:38  
标签:laravel log QueryListener 监听器 sql OperationLog uid


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

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

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

2、监听器类代码

./app/Listeners/QueryListener.php

<?php

namespace App\Listeners;

use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Http\Models\OperationLog;

class QueryListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  QueryExecuted  $event
     * @return void
     */
    public function handle(QueryExecuted $event)
    {
        $sql = str_replace("?", "'%s'", $event->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 = [
        ...
        \Illuminate\Database\Events\QueryExecuted::class => [
            'App\Listeners\QueryListener'
        ],
        ...
    ];

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

相关文章:

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


标签:laravel,log,QueryListener,监听器,sql,OperationLog,uid
From: https://blog.51cto.com/sdwml/6144714

相关文章