使用zipkin-js-instrumentation-axios集成axios和zipkin

本文介绍了一种将Zipkin分布式追踪系统与axios HTTP客户端库集成的方法,通过使用zipkin-js-instrumentation-axios库,可以在不影响axios原有功能的情况下添加追踪支持。文中详细展示了如何配置和使用该库,并说明了如何保持axios的所有特性和方法不变。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文出处:王柏元的博客>>https://wangbaiyuan.cn/zipkin-js-instrumentation-axios.html

Zipkin 是由Twitter公司开发并开源的分布式追踪系统,而axios则是常用的Javascript HTTP客户端。由于zipkin-js官方没有提供axios的适配,同时同类型库zipkin-jinstrumentation-axios已经破坏了axios的原有功能,为此极客人制作了本库用于集成zipkin和axios,可以支持axios原有的所有方法属性,其用法和axios完全一致。

Zipkin-Js-Instrumentation-Axios

Adds Zipkin tracing support for the axios JS HTTP client library. It supports all features of  axios.

Installation

 

1

npm install zipkin-js-instrumentation-axios --save

Usage

You need to use  wrapAxios fucntion to wrap the native  axios instance, and the  axios instance's type/functions/attributes are not affected. As a result, you can use  zipkinAxios the same as  axios

For example:

const axios = require('axios');

const wrapAxios = require('zipkin-js-instrumentation-axios');

const { Tracer, ExplicitContext, ConsoleRecorder } = require('zipkin');



const ctxImpl = new ExplicitContext();

const recorder = new ConsoleRecorder();

const localServiceName = 'service-a'; // name of this application

const tracer = new Tracer({ ctxImpl, recorder, localServiceName });



const remoteServiceName = 'weather-api';

const zipkinAxios = wrapAxios(axios, { tracer, localServiceName, remoteServiceName });



zipkinAxios.get('/user?ID=12345')

  .then(function (response) {

    console.log(response);

  })

  .catch(function (error) {

    console.log(error);

  });

Interceptors Of Axios Also Supported

You can intercept requests or responses before they are handled by then or catch.

 

// Add a request interceptor

axios.interceptors.request.use(function (config) {

    // Do something before request is sent

    return config;

  }, function (error) {

    // Do something with request error

    return Promise.reject(error);

  });

// Add a response interceptor

axios.interceptors.response.use(function (response) {

    // Do something with response data

    return response;

  }, function (error) {

    // Do something with response error

    return Promise.reject(error);

  });

The Test Cases All Passed

1

2

3

4

5

6

7

8

9

axios instrumentation - integration test

    ✓ should add headers to requests

    ✓ should support request shorthand (defaults to GET)

    ✓ should support both url and uri options

    ✓ should support promise callback

    ✓ should report 404 when path does not exist

    ✓ should report when service does not exist (41ms)

    ✓ should report when service returns 400

    ✓ should report when service returns 500

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值