笔记:QueryLog

基于laravel的事件实现:

笔记:QueryLog

QueryLogListener代码:

<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

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

    /**
     * Handle the event.
     *
     * @param object $event
     * @return void
     */
    public function handle(QueryExecuted $event)
    {
        //是否启用 Sql 日志
        $queryLog = config('database.query_log');
        $querySlowLogTime = config('database.query_log_slow_time');
        if ($queryLog) {
            $sql = $event->sql;
            $arg = $event->bindings;
            if ($arg) {
                foreach ($arg as $key => $value) {
                    $offset = strpos($sql, '?');
                    if ($offset !== false) {
                        if (is_int($value)) {
                            $value = (int)$value;
                        } else {
                            $value = '"' . (string)$value . '"';
                        }
                    }
                    $sql = substr_replace($sql, $value, $offset, strlen('?'));
                }
            }
            $log = vsprintf($sql, $event->bindings);
            $logStr = "sql:" . $log . "  spend_time:" . $event->time;
            if ($querySlowLogTime > 0 && $event->time >= $querySlowLogTime) {
                Log::channel('querySlowLog')->info($logStr);
            } else {
                Log::channel('queryLog')->info($logStr);
            }
        }
    }

}

config/database.php 添加配置:

    /*
     * sql logs
     */
    'query_log' => env('QUERY_LOG', false),
    'query_log_slow_time' => env('QUERY_LOG_SLOW_TIME', 0),

config/logging.php 添加配置:

        /*
         * chanel: queryLog, querySlowLog
         */
        'queryLog' => [
            'driver' => 'daily',
            'path' => storage_path('logs/query/query.log'),
            'level' => 'debug',
            'days' => 14,
        ],
        'querySlowLog' => [
            'driver' => 'daily',
            'path' => storage_path('logs/query/slow.log'),
            'level' => 'debug',
            'days' => 14,
        ],
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 5

@dingding2019 基于事件监听实现,无需调用。参考laravel事件系统:事件系统《Laravel 8 中文文档》

2年前 评论

overture 有composer包

2年前 评论

大佬,原生实现的话有什么思路没

2年前 评论

@如梦又似幻 原生一样的思路呗,不过自己实现一个观察者而已。不过既然纯原生好像也不用麻烦,搞什么监听事件了。既然DB模型或者说DB驱动你都实现了,随便加个DB日志的单列,不就想怎么玩就怎么玩了嘛。

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!