90
81

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.js ログまわり

Posted at

自前でこったことをするわけでなければ log4js-node と node-config で。

fluentd にログを送りつけたい場合は fluent-logger-node を使う。

log4js を使ってログをはきつつ、環境ごとの設定を node-config できりわける。 node-config は <environment>.json という名前で環境ごとに設定を書けるみたい。開発用と本番用でログまわりの設定を変えてみる。

基本的に以下の 3 つのログをとることにするよ。

  • アプリのシステムログ
  • アクセスログ
  • エラーログ

開発用ではすべてのレベルのログをコンソールにたれながす。

config/development.json
{
  "log4js": {
    "level": "ALL",
    "configure": {
      "appenders": [
        {
          "category": "system",
          "type": "console"
        },
        {
          "category": "access",
          "type": "console"
        },
        {
          "category": "error",
          "type": "console"
        }
      ],
      "replaceConsole": true
    }
  }
}

本番用では info 以上のログだけをファイルに記録、 fluentd 経由でログサーバーに送る。

config/production.json
{
  "log4js": {
    "level": "INFO",
    "configure": {
      "appenders": [
        {
          "category": "system",
          "type": "file",
          "filename": "logs/system.log"
        },
        {
          "category": "access",
          "type": "file",
          "filename": "logs/access.log"
        },
        {
          "category": "error",
          "type": "file",
          "filename": "logs/error.log"
        }
      ],
      "replaceConsole": true
    }
  },
  "fluentd": {
    "host": "192.168.50.120",
    "port": 24224,
    "timeout": 3.0
  }
}

で、こういう風に初期化する。モジュール化するのがいいかも。

logger.js
var config = require('config');
var log4js = require('log4js');
log4js.configure(config.log4js.configure);

if (process.env.NODE_ENV === 'production') {
    var appender = require('fluent-logger').support.log4jsAppender('node', {
        host: config.fluentd.host,
        port: config.fluentd.port,
        timeout: config.fluentd.timeout
    });
    log4js.addAppender(appender);
}

var logger = {
    system: log4js.getLogger('system'),
    access: log4js.getLogger('access'),
    error: log4js.getLogger('error')
}
for (key in logger) {
    logger[key].setLevel(config.log4js.level);
}

使うときはこんなかんじで。

logger.access.info({
    httpVersion: 1.1,
    httpMethod: 'GET',
    url: '/'
});
90
81
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
90
81

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?