首页 > 技术文章 > Laravel 中输出 SQL 语句的到 log 日志

HappyTeemo 2021-10-28 15:49 原文

在 AppServiceProvider.php 中的 boot 方法中添加如下代码 即可

 public function boot() {
        //数据库监听
        DB::listen(function ($query) {

            //排除时间
            //%Y-%m-%d %H:%i
            $tmp       = str_replace('%', '"' . '^^' . '"', $query->sql);
            $tmp       = str_replace('?', '"' . '%s' . '"', $tmp);

            $qBindings = [];
            foreach ($query->bindings as $key => $value) {
                if (is_numeric($key)) {
                    $qBindings[] = $value;
                } else {
                    $tmp = str_replace(':' . $key, '"' . $value . '"', $tmp);
                }
            }
            //var_dump($query->sql,$tmp,$qBindings);
            if (count($qBindings)) {
                $tmp = vsprintf($tmp, $qBindings);
            }
            $tmp = str_replace("\\", "", $tmp);
            if ($query->time > 1000) { //添加慢日志
                BLog::warning('use time: ' . $query->time . 'ms; ' . $tmp);
            }
            BLog::db('use time: ' . $query->time . 'ms; ' . $tmp);
        });

    }

推荐阅读