0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Node.jsで始めるWinstonロギング

Posted at

winston導入

npm install winston

ログ用設定ファイルの作成

/config/logger.tsに以下を定義

logger.ts
import winston from "winston";
import path from "path";

const env = process.env.NODE_ENV || "dev";
const logDir = process.env.LOG_DIR || "logs";

// ログレベルの定義
const levels = {
  error: 0,
  warn: 1,
  info: 2,
  http: 3,
  debug: 4,
};

// 環境に応じたログレベルを設定
const level = () => {
  return env === "dev" ? "debug" : "info";
};

// ログのフォーマットを定義
const format = winston.format.combine(
  winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
  winston.format.printf(
    (info) => `${info.timestamp} ${info.level}: ${info.message}`
  )
);

// ログの出力先を定義
const transports = [
  // エラーログファイル
  new winston.transports.File({
    filename: path.join(logDir, "app-error.log"),
    level: "error",
    format: winston.format.json(),
  }),
  // 全てのログファイル
  new winston.transports.File({
    filename: path.join(logDir, "app-all.log"),
    format: winston.format.json(),
  }),
];
// 開発環境用のコンソール出力
if (env === "dev") {
  transports.push(new winston.transports.Console());
}

// ロガーを作成
const logger = winston.createLogger({
  level: level(),
  levels,
  format,
  transports,
});

export default logger;

環境設定ファイルに以下を追加
.env

.env
NODE_ENV=dev
LOG_DIR=./logs

ログ出力方法と結果

対象のロジック内に以下のような形式で記述することができます。

import logger from "../config/logger.ts";

logger.error("データベース接続エラー", error);
logger.info("ユーザーログイン", { userId, testId });
logger.debug("変数xの値", x);

ログファイルの出力結果

app-all.log
{"level":"error","message":"データベース接続エラー","timestamp":"2025-MM-DD HH:mm:ss","error":{"message":"error xxx"}}
{"level":"info","message":"ユーザーログイン","timestamp":"2025-MM-DD HH:mm:ss","userId":"user_1","testId":"test1234"}
{"level":"debug","message":"変数xの値","timestamp":"2025-MM-DD HH:mm:ss","x":"900"}

まとめ

開発中はコンソールに詳細なログを出力してデバッグを効率化し、本番環境ではJSON形式でログファイルに記録することで、ログ解析ツールを使った運用を容易にできます。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?