morgan vs morgan-body vs winston
Node.jsアプリケーションにおけるHTTPリクエストと汎用ロギングの選択
morganmorgan-bodywinston類似パッケージ:

Node.jsアプリケーションにおけるHTTPリクエストと汎用ロギングの選択

morganmorgan-bodywinstonはいずれもNode.js環境でのロギングに使われるnpmパッケージですが、目的と機能が大きく異なります。morganはHTTPリクエストのログ専用で、Expressミドルウェアとして動作します。morgan-bodymorganを拡張し、リクエスト/レスポンスのボディ内容まで記録できるようにしたものです。一方、winstonは汎用的なロギングライブラリで、複数の出力先(ファイル、コンソール、外部サービスなど)やログレベル、フォーマットのカスタマイズに対応しています。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
morgan08,17230.6 kB349ヶ月前MIT
morgan-body010238.7 kB143年前MIT
winston024,419275 kB5204ヶ月前MIT

HTTPリクエストログ vs 汎用ロギング:morgan、morgan-body、winstonの使い分け

Node.jsアプリケーションを開発する際、ログはデバッグや監視、トラブルシューティングに欠かせません。しかし、morganmorgan-bodywinstonはそれぞれ異なる役割を持ち、混同すると設計に無駄が生まれます。ここでは、実際のコードを交えながら、それぞれの特徴と使いどころを明確にします。

📡 ログの目的:アクセスログ vs アプリケーションログ

まず、何をログに残すかで選ぶべきツールが決まります。

  • HTTPアクセスログ(誰が、いつ、どのエンドポイントにアクセスしたか)→ morgan または morgan-body
  • アプリケーション全体のイベントログ(エラー、ユーザー操作、バッチ処理など)→ winston

これらは補完関係にあり、多くの本番アプリではmorgan(またはmorgan-body)とwinstonを併用します。

🛠️ 基本的なセットアップと使い方

morgan: 標準的なHTTPアクセスログ

morganはExpress専用のミドルウェアで、一行でアクセスログを有効にできます。

// Express + morgan
const express = require('express');
const morgan = require('morgan');

const app = express();
app.use(morgan('combined')); // Apache combined format

app.get('/api/users', (req, res) => {
  res.json({ users: [] });
});

出力例:

127.0.0.1 - - [10/May/2024:12:00:00 +0000] "GET /api/users HTTP/1.1" 200 15 "-" "curl/7.68.0"

morgan-body: リクエスト/レスポンスのボディ付きログ

morgan-bodymorganを内部で使っており、追加でボディ内容を表示します。

// Express + morgan-body
const express = require('express');
const morganBody = require('morgan-body');

const app = express();
app.use(express.json());

morganBody(app); // 自動でミドルウェアを登録

app.post('/api/login', (req, res) => {
  res.json({ token: 'xxx' });
});

出力例:

[body] Request body: {"email":"test@example.com","password":"secret"}
[body] Response body: {"token":"xxx"}

⚠️ 注意: パスワードなどの機密情報が平文でログに出力されるため、本番環境での使用は避けてください。

winston: 汎用ロガー

winstonはExpressとは直接関係なく、どこでも使えるロガーです。

// Winston basic setup
const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'app.log' })
  ]
});

// どこでも使える
logger.info('User registered', { userId: 123 });
logger.error('Database connection failed', { error: err.message });

出力例(JSON形式):

{"level":"info","message":"User registered","userId":123}
{"level":"error","message":"Database connection failed","error":"ECONNREFUSED"}

🔌 Expressとの統合方法

morganwinstonを組み合わせる

多くのプロダクションアプリでは、morganでアクセスログを、winstonでアプリケーションログを記録します。morganの出力をwinstonに流すことも可能です。

const express = require('express');
const morgan = require('morgan');
const winston = require('winston');

const app = express();

const logger = winston.createLogger({
  transports: [new winston.transports.File({ filename: 'access.log' })]
});

// morganの出力をwinston経由でファイルに保存
app.use(morgan('combined', {
  stream: {
    write: (message) => logger.info(message.trim())
  }
}));

morgan-bodywinstonの併用

morgan-bodyは内部でconsole.logを使っているため、winstonと直接連携するにはカスタム設定が必要です。公式ドキュメントでは、noColors: truelogReqUserAgent: falseなどのオプションで出力を制御できますが、winstonへの統合は非公式です。

// morgan-bodyをwinstonと連携させる例(非推奨)
const originalLog = console.log;
console.log = (...args) => logger.info(args.join(' '));
morganBody(app);
console.log = originalLog; // 危険!他のモジュールに影響

このように、morgan-bodyは主に開発時の一時的なデバッグ用途に留めるのが安全です。

📊 ログの内容とセキュリティ

パッケージログ対象ボディ記録本番向きセキュリティリスク
morganHTTPメタデータのみ低い
morgan-bodyHTTPメタデータ + ボディ高い(平文で機密情報が漏れる可能性)
winston任意のアプリケーションイベント✅(手動で記録)中(開発者が適切にフィルタリングする必要あり)

🧩 拡張性とカスタマイズ

morgan: フォーマットのカスタマイズ

morganは独自のトークンシステムでフォーマットを定義できます。

morgan.token('remote-user', (req) => req.user ? req.user.id : '-');
app.use(morgan(':method :url :status :response-time ms - :remote-user'));

winston: フォーマットとトランスポートの柔軟性

winstonはフォーマットや出力先を自由に組み合わせられます。

const { combine, timestamp, label, printf } = winston.format;

const myFormat = printf(({ level, message, label, timestamp }) => {
  return `${timestamp} [${label}] ${level}: ${message}`;
});

const logger = winston.createLogger({
  format: combine(
    label({ label: 'MyApp' }),
    timestamp(),
    myFormat
  ),
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

morgan-body: カスタマイズは限定的

morgan-bodyはオプションで一部の出力を抑制できますが、フォーマットの細かい調整はできません。

morganBody(app, {
  logReqDateTime: false,
  logReqUserAgent: false,
  maxBodyLength: 1000 // ボディの最大長
});

💡 実践的なガイドライン

開発環境では?

  • デバッグ目的でHTTPボディを確認したいmorgan-bodyを一時的に有効化
  • 通常の開発morganで十分

本番環境では?

  • アクセスログmorgan + winston(ファイルまたは監視サービスへ出力)
  • アプリケーションログwinstonで統一
  • 絶対に避けることmorgan-bodyを本番で有効にしない

ログの保管と監査

  • PCI DSSやGDPRなどの規制がある場合、パスワード・トークン・個人情報をログに残してはいけません。
  • winstonを使う場合、ログ出力前に機密情報をマスクするカスタムフォーマットを作成しましょう。
// 機密情報をマスクする例
const maskToken = winston.format((info) => {
  if (info.message.includes('token')) {
    info.message = info.message.replace(/token=[^&\s]*/g, 'token=***');
  }
  return info;
});

const logger = winston.createLogger({
  format: combine(maskToken(), winston.format.json())
});

📌 まとめ

  • morgan: 軽量で安定したHTTPアクセスログ。本番環境の標準選択肢。
  • morgan-body: 開発中のデバッグ用。ボディ内容を一時的に確認したいときに便利だが、本番では使わない。
  • winston: アプリケーション全体のロギング基盤。複数の出力先、ログレベル、フォーマットを統一管理したいときに必須。

これらは競合ではなく、役割分担によって共存します。適切に使い分けることで、安全で効率的なロギング戦略を構築できます。

選び方: morgan vs morgan-body vs winston

  • morgan:

    morganは、標準的なHTTPアクセスログ(メソッド、URL、ステータスコード、レスポンスタイムなど)をシンプルに記録したい場合に最適です。Expressアプリケーションで軽量かつ安定したアクセスログが必要なとき、特に本番環境で過剰な情報を出力したくないケースに向いています。ただし、リクエストやレスポンスのボディ内容を記録する機能は含まれていません。

  • morgan-body:

    morgan-bodyは、開発中やデバッグ時にHTTP通信の詳細(特にJSONボディの中身)を確認したい場合に有効です。morganのフォーマットを拡張してボディを含めて出力してくれますが、本番環境ではセキュリティやパフォーマンスの観点から注意が必要です。個人情報や機密データが含まれる可能性があるため、本番での使用は推奨されません。

  • winston:

    winstonは、アプリケーション全体のロギング戦略を一元管理したい場合や、複数の出力先(例:コンソール+ファイル+クラウドサービス)にログを送信する必要がある場合に選ぶべきです。HTTPリクエストのログだけでなく、ビジネスロジック、エラーハンドリング、監査ログなど、あらゆる種類のログを統一されたインターフェースで扱えます。Expressとの連携には別途ミドルウェア設定が必要です。

morgan のREADME

morgan

NPM Version NPM Downloads Build Status Coverage Status

HTTP request logger middleware for node.js

Named after Dexter, a show you should not watch until completion.

Installation

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install morgan

API

var morgan = require('morgan')

morgan(format, options)

Create a new morgan logger middleware function using the given format and options. The format argument may be a string of a predefined name (see below for the names), a string of a format string, or a function that will produce a log entry.

The format function will be called with three arguments tokens, req, and res, where tokens is an object with all defined tokens, req is the HTTP request and res is the HTTP response. The function is expected to return a string that will be the log line, or undefined / null to skip logging.

Using a predefined format string

morgan('tiny')

Using format string of predefined tokens

morgan(':method :url :status :res[content-length] - :response-time ms')

Using a custom format function

morgan(function (tokens, req, res) {
  return [
    tokens.method(req, res),
    tokens.url(req, res),
    tokens.status(req, res),
    tokens.res(req, res, 'content-length'), '-',
    tokens['response-time'](https://github.com/expressjs/morgan/blob/HEAD/req, res), 'ms'
  ].join(' ')
})

Options

Morgan accepts these properties in the options object.

immediate

Write log line on request instead of response. This means that a requests will be logged even if the server crashes, but data from the response (like the response code, content length, etc.) cannot be logged.

skip

Function to determine if logging is skipped, defaults to false. This function will be called as skip(req, res).

// EXAMPLE: only log error responses
morgan('combined', {
  skip: function (req, res) { return res.statusCode < 400 }
})
stream

Output stream for writing log lines, defaults to process.stdout.

Predefined Formats

There are various pre-defined formats provided:

combined

Standard Apache combined log output.

:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"
# will output
::1 - - [27/Nov/2024:06:21:42 +0000] "GET /combined HTTP/1.1" 200 2 "-" "curl/8.7.1"
common

Standard Apache common log output.

:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]
# will output
::1 - - [27/Nov/2024:06:21:46 +0000] "GET /common HTTP/1.1" 200 2
dev

Concise output colored by response status for development use. The :status token will be colored green for success codes, red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for information codes.

:method :url :status :response-time ms - :res[content-length]
# will output
GET /dev 200 0.224 ms - 2
short

Shorter than default, also including response time.

:remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms
# will output
::1 - GET /short HTTP/1.1 200 2 - 0.283 ms
tiny

The minimal output.

:method :url :status :res[content-length] - :response-time ms
# will output
GET /tiny 200 2 - 0.188 ms

Tokens

Creating new tokens

To define a token, simply invoke morgan.token() with the name and a callback function. This callback function is expected to return a string value. The value returned is then available as ":type" in this case:

morgan.token('type', function (req, res) { return req.headers['content-type'] })

Calling morgan.token() using the same name as an existing token will overwrite that token definition.

The token function is expected to be called with the arguments req and res, representing the HTTP request and HTTP response. Additionally, the token can accept further arguments of it's choosing to customize behavior.

:date[format]

The current date and time in UTC. The available formats are:

  • clf for the common log format ("10/Oct/2000:13:55:36 +0000")
  • iso for the common ISO 8601 date time format (2000-10-10T13:55:36.000Z)
  • web for the common RFC 1123 date time format (Tue, 10 Oct 2000 13:55:36 GMT)

If no format is given, then the default is web.

:http-version

The HTTP version of the request.

:method

The HTTP method of the request.

:referrer

The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer.

:remote-addr

The remote address of the request. This will use req.ip, otherwise the standard req.connection.remoteAddress value (socket address).

:remote-user

The user authenticated as part of Basic auth for the request.

:req[header]

The given header of the request. If the header is not present, the value will be displayed as "-" in the log.

:res[header]

The given header of the response. If the header is not present, the value will be displayed as "-" in the log.

:response-time[digits]

The time between the request coming into morgan and when the response headers are written, in milliseconds.

The digits argument is a number that specifies the number of digits to include on the number, defaulting to 3, which provides microsecond precision.

:status

The status code of the response.

If the request/response cycle completes before a response was sent to the client (for example, the TCP socket closed prematurely by a client aborting the request), then the status will be empty (displayed as "-" in the log).

:total-time[digits]

The time between the request coming into morgan and when the response has finished being written out to the connection, in milliseconds.

The digits argument is a number that specifies the number of digits to include on the number, defaulting to 3, which provides microsecond precision.

:url

The URL of the request. This will use req.originalUrl if exists, otherwise req.url.

:user-agent

The contents of the User-Agent header of the request.

morgan.compile(format)

Compile a format string into a format function for use by morgan. A format string is a string that represents a single log line and can utilize token syntax. Tokens are references by :token-name. If tokens accept arguments, they can be passed using [], for example: :token-name[pretty] would pass the string 'pretty' as an argument to the token token-name.

The function returned from morgan.compile takes three arguments tokens, req, and res, where tokens is object with all defined tokens, req is the HTTP request and res is the HTTP response. The function will return a string that will be the log line, or undefined / null to skip logging.

Normally formats are defined using morgan.format(name, format), but for certain advanced uses, this compile function is directly available.

Examples

express/connect

Sample app that will log all request in the Apache combined format to STDOUT

var express = require('express')
var morgan = require('morgan')

var app = express()

app.use(morgan('combined'))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

vanilla http server

Sample app that will log all request in the Apache combined format to STDOUT

var finalhandler = require('finalhandler')
var http = require('http')
var morgan = require('morgan')

// create "middleware"
var logger = morgan('combined')

http.createServer(function (req, res) {
  var done = finalhandler(req, res)
  logger(req, res, function (err) {
    if (err) return done(err)

    // respond to request
    res.setHeader('content-type', 'text/plain')
    res.end('hello, world!')
  })
})

write logs to a file

single file

Sample app that will log all requests in the Apache combined format to the file access.log.

var express = require('express')
var fs = require('fs')
var morgan = require('morgan')
var path = require('path')

var app = express()

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

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

app.get('/', function (req, res) {
  res.send('hello, world!')
})

log file rotation

Sample app that will log all requests in the Apache combined format to one log file per day in the log/ directory using the rotating-file-stream module.

var express = require('express')
var morgan = require('morgan')
var path = require('path')
var rfs = require('rotating-file-stream') // version 2.x

var app = express()

// create a rotating write stream
var accessLogStream = rfs.createStream('access.log', {
  interval: '1d', // rotate daily
  path: path.join(__dirname, 'log')
})

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

app.get('/', function (req, res) {
  res.send('hello, world!')
})

split / dual logging

The morgan middleware can be used as many times as needed, enabling combinations like:

  • Log entry on request and one on response
  • Log all requests to file, but errors to console
  • ... and more!

Sample app that will log all requests to a file using Apache format, but error responses are logged to the console:

var express = require('express')
var fs = require('fs')
var morgan = require('morgan')
var path = require('path')

var app = express()

// log only 4xx and 5xx responses to console
app.use(morgan('dev', {
  skip: function (req, res) { return res.statusCode < 400 }
}))

// log all requests to access.log
app.use(morgan('common', {
  stream: fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
}))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

use custom token formats

Sample app that will use custom token formats. This adds an ID to all requests and displays it using the :id token.

var express = require('express')
var morgan = require('morgan')
var uuid = require('node-uuid')

morgan.token('id', function getId (req) {
  return req.id
})

var app = express()

app.use(assignId)
app.use(morgan(':id :method :url :response-time'))

app.get('/', function (req, res) {
  res.send('hello, world!')
})

function assignId (req, res, next) {
  req.id = uuid.v4()
  next()
}

License

MIT