DEV Community

KOGA Mitsuhiro
KOGA Mitsuhiro

Posted on • Originally published at qiita.com

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

はじめに

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay