1
This commit is contained in:
@@ -5,6 +5,26 @@ const logs = require("../../tool/logs_proxy");
|
||||
|
||||
const upstreamBaseUrl = config.upstream_api_url || "http://127.0.0.1:8888";
|
||||
|
||||
/** 写入日志用:序列化响应并截断,避免 TEXT 过大 */
|
||||
const RESPONSE_BODY_MAX_LEN = 16000;
|
||||
|
||||
function serialize_response_for_log(data) {
|
||||
if (data === undefined || data === null) return "";
|
||||
let s;
|
||||
if (typeof data === "string") s = data;
|
||||
else {
|
||||
try {
|
||||
s = JSON.stringify(data);
|
||||
} catch (e) {
|
||||
s = String(data);
|
||||
}
|
||||
}
|
||||
if (s.length > RESPONSE_BODY_MAX_LEN) {
|
||||
return `${s.slice(0, RESPONSE_BODY_MAX_LEN)}…[truncated]`;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转发请求到上游并记录调用日志
|
||||
* @param {object} params
|
||||
@@ -57,6 +77,7 @@ async function forwardRequest({ api_path, method, query, body, headers, auth_ctx
|
||||
http_method: method.toUpperCase(),
|
||||
status_code,
|
||||
response_time,
|
||||
response_body: serialize_response_for_log(resp_data),
|
||||
}).catch((e) => logs.error("[proxy] 写调用日志失败", e.message));
|
||||
|
||||
return { status: status_code, data: resp_data, headers: resp_headers };
|
||||
@@ -65,7 +86,15 @@ async function forwardRequest({ api_path, method, query, body, headers, auth_ctx
|
||||
/**
|
||||
* 写入 API 调用日志
|
||||
*/
|
||||
async function writeCallLog({ user_id, token_id, api_path, http_method, status_code, response_time }) {
|
||||
async function writeCallLog({
|
||||
user_id,
|
||||
token_id,
|
||||
api_path,
|
||||
http_method,
|
||||
status_code,
|
||||
response_time,
|
||||
response_body,
|
||||
}) {
|
||||
try {
|
||||
const now = new Date();
|
||||
const call_date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
|
||||
@@ -76,6 +105,7 @@ async function writeCallLog({ user_id, token_id, api_path, http_method, status_c
|
||||
http_method,
|
||||
status_code,
|
||||
response_time,
|
||||
response_body: response_body || null,
|
||||
call_date,
|
||||
created_at: now,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user