ソースを参照

请求日志增加系统分类字段

weijianghai 1 ヶ月 前
コミット
8d2e70cb7d

+ 12 - 1
scripts/openresty/lua/access.lua

@@ -1,7 +1,18 @@
+-- 引入 cjson 库,用于处理 JSON 数据
 local cjson = require "cjson"
+
+-- 获取 URL 中的查询参数(GET 请求参数)
 local args = ngx.req.get_uri_args()
+
+-- 获取当前请求的所有请求头信息
 local request_headers = ngx.req.get_headers()
+
+-- 判断请求头中是否包含 "token" 字段,或者查询参数中是否包含 "token"、"data" 或 "amp;data"
+-- 如果满足任一条件,则执行以下操作:
 if request_headers["token"] or args["token"] or args["data"] or args["amp;data"] then
+    -- 设置上下文中的 log_request 标志为 true,表示需要记录该请求
     ngx.ctx.log_request = true
+
+    -- 读取请求体内容(用于后续可能的请求体处理,如日志记录或参数解析)
     ngx.req.read_body()
-end
+end

+ 10 - 0
scripts/openresty/lua/body_filter.lua

@@ -1,8 +1,18 @@
+-- 获取当前响应的所有响应头信息
 local response_headers = ngx.resp.get_headers()
+
+-- 获取响应头中的 "content-type" 字段,若不存在则默认为空字符串
 local response_content_type = response_headers["content-type"] or ""
+
+-- 检查是否已标记需要记录请求(由之前的逻辑设置 ngx.ctx.log_request),
+-- 并且响应的内容类型为 "application/json"
 if ngx.ctx.log_request and response_content_type:match("application/json") then
+    -- 获取当前正在输出的响应数据块(body chunk)
     local chunk = ngx.arg[1]
+    -- 获取一个标志,表示是否已接收到完整的响应体(eof 表示结束)
     local eof = ngx.arg[2]
+
+    -- 如果尚未接收到完整的响应体(即不是结束阶段),则将当前数据块追加到上下文中的 response_body 中
     if not eof then
         ngx.ctx.response_body = (ngx.ctx.response_body or "") .. chunk
     end

+ 58 - 27
scripts/openresty/lua/log.lua

@@ -1,76 +1,107 @@
+-- 检查是否已标记需要记录请求(由前面的逻辑设置 ngx.ctx.log_request 为 true)
 if ngx.ctx.log_request then
+    -- 引入 cjson 库,用于将 Lua 表结构编码为 JSON 字符串
     local cjson = require "cjson"
+    -- 获取请求的 URI 参数(即 URL 查询参数)
     local args = ngx.req.get_uri_args()
+    -- 初始化 query_string 变量,用于存储查询参数的 JSON 字符串
     local query_string = ""
+    -- 使用 pcall 安全地执行编码操作,防止因数据问题导致崩溃
     pcall(function()
         query_string = cjson.encode(args)
     end)
+    -- 获取请求头信息
     local request_headers = ngx.req.get_headers()
+    -- 从请求头或查询参数中提取 token 或 data 相关字段,用于日志标识
     local token = request_headers["token"] or args["token"] or args["data"] or args["amp;data"] or ""
+    -- 获取请求内容类型
     local request_content_type = request_headers["content-type"] or ""
+    -- 获取响应头信息
     local response_headers = ngx.resp.get_headers()
+    -- 获取响应内容类型
     local response_content_type = response_headers["content-type"] or ""
+    -- 初始化请求体变量
     local request_body = ""
+    -- 如果请求内容类型为 application/json,则尝试获取请求体内容
     if request_content_type:match("application/json") then
         request_body = ngx.var.request_body or ""
     end
+    -- 初始化响应体变量
     local response_body = ""
+    -- 如果响应内容类型为 application/json,则从上下文中获取已缓存的响应体
     if response_content_type:match("application/json") then
         response_body = ngx.ctx.response_body or ""
     end
+    -- 初始化请求头的 JSON 字符串
     request_headers_json = ""
+    -- 安全地将请求头表编码为 JSON 字符串
     pcall(function()
         request_headers_json = cjson.encode(request_headers)
     end)
+    -- 初始化响应头的 JSON 字符串
     response_headers_json = ""
+    -- 安全地将响应头表编码为 JSON 字符串
     pcall(function()
         response_headers_json = cjson.encode(response_headers)
     end)
+
+    -- 引入 resty.logger.socket 模块,用于异步发送日志
     local logger = require "resty.logger.socket"
+    -- 检查 logger 是否已经初始化
     if not logger.initted() then
+        -- 如果未初始化,则进行初始化配置
         local ok, err = logger.init{
-            host = "127.0.0.1",
-            port = 39876,
-            sock_type = "tcp",
-            flush_limit = 10240,
-            drop_limit = 1048576,
-            timeout = 1000,
-            max_retry_times = 3,
-            retry_interval = 10000
+            host = "127.0.0.1",           -- 日志接收服务器地址
+            port = 39876,                 -- 日志接收端口
+            sock_type = "tcp",            -- 使用 TCP 协议
+            flush_limit = 10240,          -- 缓冲区刷新阈值(字节)
+            drop_limit = 1048576,         -- 超过此值则丢弃新日志
+            timeout = 1000,               -- 发送超时时间(毫秒)
+            max_retry_times = 3,          -- 最大重试次数
+            retry_interval = 10000        -- 重试间隔(毫秒)
         }
+        -- 如果初始化失败,记录错误日志并退出
         if not ok then
             ngx.log(ngx.ERR, "Logger初始化失败: ", err)
             return
         end
     end
+
+    -- 构建要记录的日志数据结构(Lua 表)
     local log_data = {
-        access_time = ngx.var.time_iso8601,
-        status = ngx.var.status,
-        request_time = ngx.var.request_time,
-        uri = ngx.var.uri,
-        query_string = query_string,
-        request_body = request_body,
-        request_headers = request_headers_json,
-        response_headers = response_headers_json,
-        response_body = response_body,
-        token = token,
-        request_method = ngx.var.request_method,
-        scheme = ngx.var.scheme,
-        server_protocol = ngx.var.server_protocol,
-        request_length = ngx.var.request_length,
-        body_bytes_sent = ngx.var.body_bytes_sent,
-        bytes_sent = ngx.var.bytes_sent,
-        http_x_real_ip = ngx.var.http_x_real_ip,
-        http_x_forwarded_for = ngx.var.http_x_forwarded_for,
-        remote_addr = ngx.var.remote_addr
+        access_time = ngx.var.time_iso8601,            -- 访问时间(ISO8601 格式)
+        status = ngx.var.status,                       -- HTTP 状态码
+        request_time = ngx.var.request_time,           -- 请求处理时间(秒)
+        uri = ngx.var.uri,                             -- 请求的 URI
+        query_string = query_string,                   -- 查询参数(JSON 字符串)
+        request_body = request_body,                   -- 请求体内容
+        request_headers = request_headers_json,        -- 请求头(JSON 字符串)
+        response_headers = response_headers_json,      -- 响应头(JSON 字符串)
+        response_body = response_body,                 -- 响应体内容
+        token = token,                                 -- 提取的 token 或 data 信息
+        request_method = ngx.var.request_method,       -- 请求方法(GET、POST 等)
+        scheme = ngx.var.scheme,                       -- 协议(http 或 https)
+        server_protocol = ngx.var.server_protocol,     -- 使用的协议版本(如 HTTP/1.1)
+        request_length = ngx.var.request_length,       -- 请求长度(字节)
+        body_bytes_sent = ngx.var.body_bytes_sent,     -- 发送给客户端的响应体字节数
+        bytes_sent = ngx.var.bytes_sent,               -- 总共发送的字节数
+        http_x_real_ip = ngx.var.http_x_real_ip,       -- X-Real-IP 请求头
+        http_x_forwarded_for = ngx.var.http_x_forwarded_for, -- X-Forwarded-For 请求头
+        remote_addr = ngx.var.remote_addr              -- 客户端真实 IP 地址
     }
+
+    -- 使用 pcall 安全地将 log_data 编码为 JSON 字符串
     local success, result = pcall(cjson.encode, log_data)
     if not success then
+        -- 如果编码失败,打印错误信息并返回
         print("JSON编码失败: ", result)
         return
     end
+
+    -- 将编码后的 JSON 日志数据加上换行符发送出去
     local bytes, err = logger.log(result .. "\n")
     if err then
+        -- 如果发送失败,记录错误日志
         ngx.log(ngx.ERR, "日志发送失败: ", err)
     end
 end

+ 27 - 0
scripts/restore-financialdb.ps1

@@ -0,0 +1,27 @@
+param (
+    [string]$backup_dir = $(throw "请提供备份目录作为第一个参数")
+)
+
+# 设置环境变量
+$env:PGPASSWORD = 'postgres'
+
+$host_ = '127.0.0.1'
+$port = '5432'
+$username = 'postgres'
+$dbname = 'financialdb'
+$jobs = '16'
+
+# 检查数据库是否存在
+$checkDbExists = psql -U $username -tA -c "SELECT 1 FROM pg_database WHERE datname='$dbname'" | Out-String
+
+if ($checkDbExists.Trim() -ne "1") {
+    Write-Output "数据库 $dbname 不存在,正在创建..."
+    createdb -U $username $dbname
+} else {
+    Write-Output "数据库 $dbname 已存在。"
+}
+
+# 执行 pg_restore
+Write-Output "开始从 $backup_dir 恢复数据库 $dbname..."
+
+pg_restore -O -c -v -h $host_ -p $port -U $username -d $dbname -Fd -j $jobs $backup_dir

+ 3 - 0
scripts/restore-financialdb.sh

@@ -7,4 +7,7 @@ port='5432'
 username='finance'
 dbname='financialdb'
 jobs='16'
+if [ "$(psql -U ${username} -tAc "SELECT 1 FROM pg_database WHERE datname='${dbname}'")" != "1" ]; then
+    createdb -U ${username} ${dbname}
+fi
 pg_restore -O -c -v -h "${host}" -p "${port}" -U "${username}" -d "${dbname}" -Fd -j "${jobs}" "${backup_dir}"

+ 4 - 0
src/main/java/com/nokia/finance/tasks/pojo/po/common/NginxLogPo.java

@@ -135,4 +135,8 @@ public class NginxLogPo {
      * 客户端IP地址
      */
     private String remoteAddr;
+    /**
+     * 系统类型
+     */
+    private String systemType;
 }

+ 0 - 65
src/main/java/com/nokia/finance/tasks/pojo/po/common/RequestLogPo.java

@@ -1,65 +0,0 @@
-package com.nokia.finance.tasks.pojo.po.common;
-
-import com.baomidou.mybatisplus.annotation.TableName;
-import lombok.Data;
-import lombok.NoArgsConstructor;
-
-import java.time.LocalDateTime;
-
-@NoArgsConstructor
-@Data
-@TableName("common.request_log")
-public class RequestLogPo {
-    /**
-     * 请求时间
-     */
-    private LocalDateTime requestTime;
-
-    /**
-     * 账号,从token解密
-     */
-    private String loginId;
-
-    /**
-     * 页面url,从token解密
-     */
-    private String pageUrl;
-
-    /**
-     * 接口url
-     */
-    private String api;
-
-    /**
-     * 请求参数
-     */
-    private String requestParameters;
-
-    /**
-     * 请求头
-     */
-    private String headers;
-
-    /**
-     * 应用id,从token解密
-     */
-    private String appId;
-
-    /**
-     * 时间戳,从token解密
-     */
-    private LocalDateTime timeStamp;
-
-    /**
-     * 访问令牌
-     */
-    private String token;
-    /**
-     * 过期秒数,从token解密
-     */
-    private Integer expireTime;
-    /**
-     * 过期时间
-     */
-    private LocalDateTime expireTimeStamp;
-}

+ 11 - 0
src/main/java/com/nokia/finance/tasks/service/common/NginxLogService.java

@@ -127,6 +127,17 @@ public class NginxLogService implements SmartLifecycle {
                                     po.setTimeStamp(timeStamp);
                                     po.setExpireTime(expireTime);
                                     po.setExpireTimeStamp(expireTimeStamp);
+                                    String systemType = "";
+                                    if (po.getUri().contains("house-car/house")) {
+                                        systemType = "house";
+                                    } else if (po.getUri().contains("house-car/car")) {
+                                        systemType = "car";
+                                    } else if (po.getPageUrl().contains("house-car/house")) {
+                                        systemType = "house";
+                                    } else if (po.getPageUrl().contains("house-car/car")) {
+                                        systemType = "car";
+                                    }
+                                    po.setSystemType(systemType);
                                     // 将日志对象插入数据库
                                     nginxLogDao.insert(po);
                                 }