实现一个http请求的日志管理器

612 阅读2分钟

这是我参与2022首次更文挑战的第28天,活动详情查看:2022首次更文挑战」。

1.需求背景和功能设计

我们在做web开发的时候,在单页应用兴起的现在,ajax请求越来越多,我们需要一个更好用也更强大的http请求库。这个请求库可以在web页面也可以在nodejs中使用。恰恰最流行的http开源请求库就是axios,但是对于平时我们的请求日志全靠axios报错抛出来进行判定,我们很多时候需要自定义很多日志用于区分不同接口,不同时间,不同环境。

基于开源axios-logger,在 nodejs 中发送请求时,可以将日志显示到终端。在web浏览器中发送请求的时候,可以将日志打印在控制台中。

2.日志分类

请求日志主要分为请求过程信息,响应过程信息,错误过程信息三类。主要实现思路是在axios请求拦截器中进行请求信息获取,响应拦截器中进行响应信息获取,在拦截器错误处理中获取必要的错误信息。

请求

instance.interceptors.request.use((request) => {
    // write down your request intercept.
    return AxiosLogger.requestLogger(request);
});

响应

instance.interceptors.response.use((response) => {
    // write down your response intercept.
    return AxiosLogger.responseLogger(response);
});

错误

instance.interceptors.request.use(AxiosLogger.requestLogger, AxiosLogger.errorLogger);
instance.interceptors.response.use(AxiosLogger.responseLogger, AxiosLogger.errorLogger);

3.必要信息采集

对于具体的信息才开,给出灵活的配置。

PropertyTypeDefaultDescription
methodbooleantrueWhether to include HTTP method or not.
urlbooleantrueWhether to include the URL or not.
paramsbooleanfalseWhether to include the URL params or not.
databooleantrueWhether to include request/response data or not.
statusbooleantrueWhether to include response statuses or not.
headersbooleanfalseWhether to include HTTP headers or not.
prefixTextstring false'Axios'false => no prefix, otherwise, customize the prefix wanted.
dateFormatdateformat  falsenew Date().toISOString()false => no timestamp, otherwise, customize its format
loggerfunction<string, any>console.logAllows users to customize the logger function to be used. e.g. Winston's logger.info could be leveraged, like this: logger.info.bind(this)

4.自定义输出记录器功能

在第三点中提到了logger可以自定义,那我们可以自定义一个logger,首先这个logger我是基于console.log的二次封装,第一点就是颜色控制,对于颜色控制我们可以想到nodejs中的chalk,但是chalk有个问题是不能在浏览器中打印出颜色,所以只能借用console.log第一个参数类型来实现.

枚举类型定义

export enum ColorType {
  GREEN = '\x1B[32m%s\x1B[39m',
  BLUE = '\x1B[34m%s\x1B[39m',
  RED = '\x1B[31m%s\x1B[39m',
  BLACK = '\x1B[30m%s\x1B[39m'
}

颜色工具类

// 颜色打印工具类
export function colorLogger(text: string, color: string = ColorType.BLACK) {
  return console.log(color, text)
}

5.解析参数

  function requestLogger(
  request: AxiosRequestConfig,
  config: RequestLogConfig = {}
) {
  const { baseURL, url, params, method, data, headers } = request
  const buildConfig = assembleBuildConfig(config)

  const mainLogger = new MainLogger(config)
  const logText = mainLogger
    .logPrefix('Request')
    .logDate(new Date())
    .logMethods(method)
    .logFullUrl(url, baseURL)
    .logParams(params)
    .logHeaders(headers)
    .logData(data)
    .build()

  buildConfig.logger(logText, ColorType.BLUE)
}

提供了将接收的参数进行格式化标准的方法,最后形成的格式为下图介绍

image.png