@uswitch/koa-zipkin

🕵️‍♀️ A koa.js middleware to add Zipkin tracing to requests

Usage no npm install needed!

<script type="module">
  import uswitchKoaZipkin from 'https://cdn.skypack.dev/@uswitch/koa-zipkin';
</script>

README

🤐 Koa Zipkin

A Koa middleware for wiring into zipkin.js

Overview | Usage | Api

Contributors License type language test style

Overview

This package is a Koa library to do a lot of the heavy lifting to enable zipkin tracing around your service and of upstream requests within your app.

It tries to encapsulate some of the run time mentality of how you build a service with the compile time integration of `zipkin.js** libraries and instrumentations.


N.B. - This library is opinionated. It provides;

Usage

Using a fetch client without a cache

This is the simplest way to get zipkin tracing working with a koa application and sending to a Zipkin server.

// Define a module `zipkin.js`

import { middleware, fetch, Logger, Tracer } from '@uswitch/koa-zipkin'
import fetch from 'node-fetch'

const { middleware, fetch, Logger, Tracer } = koaZipkin
const { NODE_ENV, ZIPKIN_HOST, APP_NAME = 'example-service' } = process.env

const logger = Logger({ local: NODE_ENV === 'development', endpoint: ZIPKIN_HOST })
const tracer = Tracer(APP_NAME, logger)

export const zipkin = middleware({ tracer })
export const zipkinFetch = fetch({ local: APP_NAME, client: fetch, tracer })

// ----------------------------------------
// Then in your `koa` server you can just use
import { zipkin, zipkinFetch } from './zipkin'

app.use(zipkin)

app.use((ctx, next) => zipkinFetch({ remote: 'my-upstream' }, 'http://my-upstream'))

Using axios with a cache

Similarly to above, there are some benefits to using axios with its cache adapter. You get added logging of cache hits and misses as well as the zipkin tracing. However, this needs a few extra bits like adding the X-Cache-Enabled:true header to your responses.

// Define a module `zipkin.js`
import koaZipkin from '@uswitch/koa-zipkin'

import axios from 'axios'
import cache from 'axios-cache-adapter'

const { middleware, fetch, Logger, Tracer } = koaZipkin
const { USE_CACHE = true, NODE_ENV, APP_NAME = 'example-uf-service' } = process.env

const { adapter } = cache.setupCache({ maxAge: USE_CACHE ? 10 * 1000 : 0 })
const client = axios.create({ adapter })

/* Mark the intent of using a cache */
client.interceptors.response.use(
  (res) => {
    res.headers['X-Cache-Enabled'] = true
    return res
  },
  Promise.reject
)

const tracer = Tracer(APP_NAME, Logger({ local: NODE_ENV === 'development' }))

export const zipkin = middleware({ tracer })
export const zipkinFetch = fetch({ local: APP_NAME, client, tracer })