New Relic APMをNode.jsに導入する

2022-05-20

Node.js アプリケーションに New Relic APM を導入したのでメモとして記事に残します。

設定

Express.js と Winston を利用した簡易なアプリケーションを例にします。

$ npm init
$ npm install newrelic winston @newrelic/winston-enricher express --save

各種バージョン情報

$ node -v  
v16.15.0
$ npm -v
8.5.5
$ npm info newrelic version
8.11.1
$ npm info winston version
3.7.2
$ npm info @newrelic/winston-enricher version
3.1.1
$ npm info express version
4.18.1

なお、 Node.js の New Relic モジュールは 8.11.0以降 にログ転送機能がサポートされます。

コード

コードは以下の 2 種類を準備します。
各ファイルはプロジェクトのルートディレクトリにフラットに配置するものとします。

  • newrelic.js
  • sample.js

newrelic.js

/node_modules/newrelic/newrelic.js からコピーしてきたものを編集して利用します。
app_namelicense_key が必須設定です。

'use strict'

exports.config = {
  app_name: ['sample-nodejs'], // 必須設定
  license_key: 'license key',  // 必須設定
  logging: {
    level: 'info'
  },
  allow_all_headers: true,
  application_logging: {
    forwarding: {
      enabled: true
    }
  },
  attributes: {
    exclude: [
      'request.headers.cookie',
      'request.headers.authorization',
      'request.headers.proxyAuthorization',
      'request.headers.setCookie*',
      'request.headers.x*',
      'response.headers.cookie',
      'response.headers.authorization',
      'response.headers.proxyAuthorization',
      'response.headers.setCookie*',
      'response.headers.x*'
    ]
  }
}

sample.js

Express.js と Winston を利用した簡易なアプリケーションを例にします。
先に例にあげた newrelic.js をロードできるように require('./newrelic') を記載しておくのがポイントです。

require('./newrelic') // newrelic.js のロード

// ロガーの設定
const winston = require('winston');
const newrelicFormatter = require('@newrelic/winston-enricher')(winston)
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    newrelicFormatter(),
    winston.format.json()
  ),
  transports: new winston.transports.Console()
});

// Express.js の設定
const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  logger.info('You access / .'); // Winston によるログ出力
  res.send('Hello World!')
})

app.get('/health', (req, res) => {
  logger.info('You access /health .'); // Winston によるログ出力
  res.send('healty')
})

app.listen(port, () => {
  logger.info(`Example app listening on port ${port}`); // Winston によるログ出力
})

実行方法は以下の通りです。

$ node sample.js

おすすめ書籍

おすすめ記事