cannot get request id with koa-morgan
renjuen opened this issue · 2 comments
renjuen commented
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
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
Thanks for sharing the workaround! Unfortunately, not all libraries play nicely with ALS.