LoginSignup
11
8

More than 3 years have passed since last update.

Expressのmorganと他のロガーを連携する

Last updated at Posted at 2016-04-11

はじめに

Node.jsのWebフレームワークExpressはexpress-generatorを使うとアプリケーションの雛形を作成してくれます。
この雛形はHTTPリクエストロガーのmorganが含まれていますが、メッセージフォーマットくらいしかカスタマイズできません。
そこで他のロガーと連携してみました。ここではwinstonを使ってみます。

連携方法

GitHubのページでは以下のようにstreamプロパティでファイルに出力しています。

expressjs/morgan # write logs to a file

// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(__dirname + '/access.log', {flags: 'a'})

// setup the logger
app.use(morgan('combined', {stream: accessLogStream}))

このstreamプロパティがどのように使われているのか追跡すると以下のようにwrite関数を呼び出しています。

morgan / index.js#L130

stream.write(line + '\n')

つまり、次のような形で他のロガーと連携できるはずです。

app.use(require('morgan')({
    stream: {
        write: function(message) {
            // ここでmessageをログ出力すればよい!
        }
    }})
);

winstonと連携する

winstonのカスタムロガーと連携する場合は以下のようなコードになります。

// winstonでカスタムロガー作成
var winston = require('winston');
winston.emitErrs = true;

var logger = new winston.Logger({
    level: 'info',
    transports: [
        new (winston.transports.Console)({
            level: 'silly',
            handleExceptions: true,
            json: false,
            colorize: true
        }),
        new (winston.transports.File)({
            handleExceptions: true,
            json: false,
            colorize: false,
            filename: './logs/all-logs.log'
        })
    ]
});

// 連携用のwrite関数
logger.stream = {
    write: function (message) {
        logger.info(message);
    }
};

// morganと連携
app.use(require('morgan')({stream: logger.stream}));

// アプリログはlogger.info()などで出力する

参考

stackoverflow # Node.js - logging / Use morgan and winston

11
8
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
11
8