简体   繁体   English

记录 axios 请求和响应标头

[英]Logging axios request and response headers

We are needing log the HTTP request that axios will send to the remote host, along with the response.我们需要记录 axios 将发送到远程主机的 HTTP 请求以及响应。 This data will be stored in a database for a number of days before being automatically pruned.在自动修剪之前,这些数据将在数据库中存储数天。

The lifecycle we are looking at for the logging:我们正在查看日志记录的生命周期:

// 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);

We have looked at the request and response interceptors, but the issue we are having is that the request interceptor is before axios adds all the headers is going to send and the response interceptor doesn't seem to have access to the request, to be able to correlate the request and response.我们已经查看了请求和响应拦截器,但我们遇到的问题是请求拦截器在 axios 添加所有要发送的标头之前,响应拦截器似乎无法访问请求,能够关联请求和响应。

Without needing to channel all this through a proxy to do the logging, how would you suggest doing this with axios?无需通过代理引导所有这些来进行日志记录,您如何建议使用 axios 执行此操作?

Here's what I usually do:这是我通常做的:

In the request interceptor, I use some UUID library (or maybe the crypto core module of node) to generate a UUID, then attach it to the config object as a request ID, say config.reqId .在请求拦截器中,我使用一些 UUID 库(或者可能是节点的crypto核心模块)来生成 UUID,然后将其附加到config object 作为请求 ID,比如config.reqId Same config object should be accessible in response.config , or if an error occurs, in error.response.config and I can get the reqId from there.相同的配置 object 应该可以在response.config中访问,或者如果发生错误,在error.response.config中,我可以从那里获取 reqId。 Then, if you have some script to parse the logs, you can correlate the request and response using this ID.然后,如果您有一些脚本来解析日志,您可以使用此 ID 关联请求和响应。

The disadvantage here is that, yes, the accurate req headers may not be logged.这里的缺点是,是的,可能不会记录准确的请求标头。

Also, if you're just looking for the request object in response, then they should be accessible in response.request , going from what I checked in the axios docs .此外,如果您只是在寻找请求 object 作为响应,那么它们应该可以在response.request中访问,这来自我在 axios 文档中检查的内容 You can try that out.你可以试试看。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM