diff --git a/app/controller/BpsAdController.php b/app/controller/BpsAdController.php index f05c60f..d6a77f4 100644 --- a/app/controller/BpsAdController.php +++ b/app/controller/BpsAdController.php @@ -200,6 +200,7 @@ class BpsAdController // 调用 Service 层查询广告列表 + $this->adsInsightService::enableSqlLog(); $result = $this->adsInsightService::getAccountList( $platformType, // 平台类型 $options['jwtClaims']['merchant_id'], // 店铺 @@ -321,6 +322,7 @@ class BpsAdController // 获取客户ID数组 $accountIds = array_column($accounts, 'account_id'); // 调用 Service 层查询 + $this->adsInsightService::enableSqlLog(); $result = $this->adsInsightService::getCampaignList( $platformType, $accountIds, // 客户 ID 数组 diff --git a/app/service/AdsInsightService.php b/app/service/AdsInsightService.php index 7a6dab3..72f6cad 100644 --- a/app/service/AdsInsightService.php +++ b/app/service/AdsInsightService.php @@ -25,9 +25,13 @@ use think\db\exception\DbException; use think\facade\Db as ThinkDb; use support\Redis; use support\Response; +use support\Log; class AdsInsightService { + // 在类顶部添加 + private static $sqlLogEnabled = false; + // 状态映射数组 private static $statusMapping = [ 0 => 'UNSPECIFIED', // UNSPECIFIED @@ -2090,4 +2094,32 @@ class AdsInsightService return $platformMapping[$thirdType] ?? null; // 如果不存在的第三方类型,返回 null } + private static function getLastQueryParams() + { + $query = ThinkDb::getLastQuery(); + return $query ? $query->getOptions()['where'] : []; + } + + // 修改enableSqlLog方法 + public static function enableSqlLog() + { + if (!self::$sqlLogEnabled) { + ThinkDb::listen(function($sql, $time, $explain) { + $logData = [ + 'sql' => $sql, + 'time' => $time . 'ms', + 'params' => self::getLastQueryParams(), + 'trace' => debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5) + ]; + // 仅在非空时记录 EXPLAIN + if (!empty($explain)) { + $logData['explain'] = $explain; + } + + Log::channel('sql')->debug('SQL', $logData); + }); + self::$sqlLogEnabled = true; + } + } + } diff --git a/config/log.php b/config/log.php index 7f05de5..c43bc65 100644 --- a/config/log.php +++ b/config/log.php @@ -12,6 +12,8 @@ * @license http://www.opensource.org/licenses/mit-license.php MIT License */ +use Monolog\Formatter\JsonFormatter; + return [ 'default' => [ 'handlers' => [ @@ -29,4 +31,22 @@ return [ ] ], ], + 'channels' => [ + 'sql' => [ + 'handlers' => [ + [ + 'class' => Monolog\Handler\RotatingFileHandler::class, + 'constructor' => [ + runtime_path() . '/logs/sql.log', // SQL专用日志 + 7, + Monolog\Logger::DEBUG, + ], + 'formatter' => [ + 'class' => Monolog\Formatter\JsonFormatter::class, // JSON格式方便分析 + 'constructor' => [JsonFormatter::BATCH_MODE_JSON, true], + ], + ] + ], + ], + ], ];