记录 axios 请求和响应标头

And*_*e M 2 node.js axios

我们需要记录 axios 将发送到远程主机的 HTTP 请求以及响应。这些数据将在数据库中存储几天,然后被自动删除。

我们正在查看的日志记录的生命周期:

// creates the session that joins both the request and response
function createSession (url: string): string;
// log the request message as sent
function logRequest (sessionId: string, headers: Record<string, any>, body: Record<string, any> | string);
// log the request message as received
function logResponse (sessionId: string, headers: Record<string, any>, body: Record<string, any> | string);
// close the session, recording the final status and any error message
function closeSession(sessionId: string, status: number, error?: string);
Run Code Online (Sandbox Code Playgroud)

我们已经研究了请求和响应拦截器,但我们遇到的问题是请求拦截器是在 axios 添加所有要发送的标头之前,而响应拦截器似乎无法访问请求,从而能够关联请求和响应。

无需通过代理来进行所有这些操作来进行日志记录,您建议如何使用 axios 来完成此操作?

Anu*_*oli 6

这是我通常做的事情:

在请求拦截器中,我使用一些UUID库(或者可能是crypto节点的核心模块)来生成UUID,然后将其config作为请求ID附加到对象,例如config.reqId。相同的配置对象应该可以在 中访问response.config,或者如果发生错误,在 中error.response.config,我可以从那里获取 reqId。然后,如果您有一些脚本来解析日志,则可以使用此 ID 关联请求和响应。

这里的缺点是,是的,可能不会记录准确的请求头。

另外,如果您只是在响应中查找请求对象,那么根据我在 axios 文档中检查的内容,它们应该可以在 中访问response.request。你可以尝试一下。

const axios = require("axios");
const getNewUuid = require("./someUuidGeneratorUtilFunction.js");
const logger = require('./yourChoiceOfLogger.js');

const config = {
    BASE_URL: "https://your.baseurl.here"
}

const myAxiosInstance = axios.create({
    baseURL: config.BASE_URL,
    timeout: 30000,
})

myAxiosInstance.interceptors.request.use((config) => {
    const customUuid = getNewUuid();
    config.reqId = customUuid;
    const message = {
        reqId: customUuid,
        time: Date.now(),
        config: config
    }

    logger.info(message)
    return config;
})

myAxiosInstance.interceptors.response.use((response) => {
    const customUuid = response.config && response.config.reqId ? response.config.reqId : "";
    const message = {
        reqId: customUuid,
        time: Date.now(),
        status: response.status,
        data: response.data,
        headers: response.headers,
        logMessage: "RESPONSE RECEIVED"
    }
    logger.info(message)
    return response;
},(error) => {
    const customUuid = error.response && error.response.config && error.response.config.reqId ? error.response.config.reqId : "";
    
    const errorResponse = error.response ? error.response : {
        status: null,
        data: null,
        headers: null
    }
    const message = {
        reqId: customUuid,
        time: Date.now(),
        status: errorResponse.status,
        data: errorResponse.data,
        headers: errorResponse.headers,
        logMessage: error.message || "ERROR"
    }
    logger.error(message)
    return Promise.reject(error)
})

module.exports = myAxiosInstance;
Run Code Online (Sandbox Code Playgroud)