Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cannot get request id with koa-morgan #66

Open
renjuen opened this issue Feb 23, 2023 · 2 comments
Open

cannot get request id with koa-morgan #66

renjuen opened this issue Feb 23, 2023 · 2 comments

Comments

@renjuen
Copy link

renjuen commented Feb 23, 2023

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
Copy link
Author

renjuen commented Feb 23, 2023

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
Copy link
Owner

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

@renjuen renjuen changed the title can get request id with koa-morgan cannot get request id with koa-morgan Feb 23, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants