puzpuzpuz / cls-rtracer

Request Tracer - CLS-based request id generation for Express, Fastify, Koa and Hapi, batteries included
MIT License
311 stars 24 forks source link

cannot get request id with koa-morgan #66

Open renjuen opened 1 year ago

renjuen commented 1 year ago

So I am trying to include the request-id in my logging, but it doesn't work with koa-morgan.

Here's my code:

import Koa from "koa"
import morgan from "koa-morgan"
import rTracer from "cls-rtracer"

const app = new Koa()
app.use(rTracer.koaMiddleware())
app.use(getMorgan())

app.use(() => {
  console.log("it works here", getReqId())
})

app.listen(8080)

const getReqId = () => {
  return (rTracer.id() ?? "") as string
}

const getMorgan = () => {
  morgan.token("reqId", getReqId)
  return morgan("it doesn't work here  :reqId")
}

then when I run the app

> curl --location --request GET 'localhost:8080/'

it works here fc7170b0-b328-11ed-b4d4-11d1313525c1
it doesn't work here -
renjuen commented 1 year ago

I end up setting the echoHeader option to true and getting the request-id from the response header. Works for me.

import Koa from "koa"
import morgan from "koa-morgan"
import rTracer from "cls-rtracer"

const app = new Koa()
app.use(rTracer.koaMiddleware({
    echoHeader: true,
  })
)
app.use(getMorgan())

app.use(() => {
  console.log("it works here", getReqId())
})

app.listen(8080)

const getReqId = () => {
  return (rTracer.id() ?? "") as string
}

const getMorgan = () => {
  morgan.token("reqId", (req, res) => {
    return (res.getHeader("x-request-id") ?? "") as string
  })
  return morgan("now it works :reqId")
}
puzpuzpuz commented 1 year ago

Thanks for sharing the workaround! Unfortunately, not all libraries play nicely with ALS.