筆記:QueryLog

Diego_crazy發表於2021-08-12

基於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 協議》,轉載必須註明作者和本文連結