nksaraf / vinxi

The Full Stack JavaScript SDK
https://vinxi.vercel.app
MIT License
1.33k stars 57 forks source link

How to add instrumentation to vinxi powered app? #311

Open asterikx opened 2 weeks ago

asterikx commented 2 weeks ago

I would like to add Open Telemetry to a Solid Start application powered by vinxi for full-stack observability and performance tracing.

Is there something like an instrumentation.ts file like in Next.js (see here) or a special hook to register Open Telemetry with auto-instrumentation?

nksaraf commented 2 weeks ago

I think we should try to make this something thats really simple to do as well. I haven't thought about it enough, but there are enough hooks in the system to do anything during the lifecycle. So its definetely possible to do. For eg. in my app, I added request/response logging like this during dev..

  app.hooks.hook("app:dev:server:created", ({ devApp }) => {
    let reqId = 0

    let regex = /(\/@)|(\/node_modules)|(\/(src|fonts|__)).*/
    devApp.h3App.options.onRequest = (event) => {
      if (regex.exec(event.path)) return
      let id = ++reqId
      console.log(
        `${new Date().toISOString()} 📞 ${id} ${event.method} ${event.path}`,
      )
      event.context.id = id
      event.context.requestStartTime = Date.now()
    }
    devApp.h3App.options.onAfterResponse = (event, response) => {
      if (regex.exec(event.path)) return
      let elapsed = Date.now() - event.context.requestStartTime
      console.log(
        `${new Date().toISOString()} 📬 ${event.context.id} ${event.method} ${event.path} ${event.node.res.statusCode} ${event.node.res.getHeader("content-type")} ${elapsed}ms`,
      )
    }
  })

This is just an example of what kind of hooks are available. During prod, you will be able to use a nitro plugin to do the same.

Actually maybe we should enable doing the same by playing the plugins during dev too which we have been planning to do.