Alongkorn Chetasumon Alongkorn Chetasumon - 2 months ago 20
Node.js Question

how to configure newrelic on node + koa app

I have an application using node.js, koa, koa-router.
I want to add newrelic to my application, but it does not support koa.

So I tried to utilise koa-newrelic (https://github.com/AfterShip/koa-newrelic) but it still does not work.

i still get

/*
for all transactions.

who have experience about this?

Answer

my colleague helps me to solve this issue.

the solution is below

1.declare custom koa new relic here

//****************** myKoaNewRelic.js *****************
'use strict'

module.exports = function monitor(router, newrelic) {
  return function* monitor(next) {
    const route = this.params[0]
    for (const layer of router.stack) {
      if (layer.path !== '(.*)') {
        const method = (layer.methods.indexOf('HEAD') !== -1) ? layer.methods[1] : layer.methods[0]
        if (route.match(layer.regexp) && method === this.request.method) {
          newrelic.setControllerName(layer.path, method)
        }
      }
    }
    yield next
  }
}

2.update main index.js like this

//****************** index.js *****************
'use strict'    

const newrelic = require('newrelic')
const koaNewrelic = require('./myKoaNewRelic')
const app = require('koa')()
const router = require('koa-router')()

router.use(koaNewrelic(router, newrelic))

// DO SOME STUFF