LoginSignup
0
0

More than 3 years have passed since last update.

Winstonでログを出力する

Posted at

インストール

npm i winston
npm i -D @types/winston

設定ファイル

logger.ts
import * as winston from "winston";

export class Logger {
  // クラス変数(this.~)・インスタンス変数の型宣言
  private logger: winston.Logger;
  private stage: string;

  // Loggerインスタンス作成時に設定する項目(インスタンス変数)
  constructor(stage: string) {
    this.stage = stage;
  }

  public async initialize(): Promise<winston.Logger> {
    this.logger = winston.createLogger({
      level: "info",
      format: winston.format.combine(
        winston.format.timestamp({
          format: "YYYY-MM-DD HH:mm:ss"
        }),
        winston.format.errors({ stack: true }),
        winston.format.splat(),
        winston.format.json()
      ),
      // デフォルトで毎回必ず出力する項目を設定(出力時変更不可)
      defaultMeta: {
        service: "winston-lambda"/*
        *他にも
        *constuructorで設定した値(this.label = 'sample label')を
        *ここで
        *label: this.label
        *として設定してもよい
        *(つまりインスタンス作成時に値を設定してそれを毎回出力する)
        */
      },
      transports: new winston.transports.Console()
    });

    // 検証環境の場合、loggingをdebugレベルまで上げる
    if (this.stage !== "prd") {
      // clear()をする事によって、createLoggerの際に指定したtransportsの設定を消せる
      this.logger.clear();
      this.logger.add(
        new winston.transports.Console({
          level: "debug"
        })
      );
    }
    return this.logger;
  }
}

使用する

sample.ts
import Logger from './logging/logger';

// 元になるインスタンスを作成して初期化
const originalLogger = new Logger('dev').initialize();

// childメソッドを使ってインスタンスを分けることで、エラー出力時など、たまに切り替える項目の値を切り替える
// これで通常はlogger.logやlogger.infoなどと、console.log()と同じように簡易にログが出力できる
const logger = originalLogger.child({ notice: 0 });
const loggerWithNotice = originalLogger.child({ notice: 1 });

// 通常の出力方法
logger.log({
  level: "info",
  message: "SILLY message",
  additional_label: "additional_content" // オブジェクトに値を追加することで出力内容を随時追加できる
});

// logメソッドではなく、直接レベル名を繋ぐことで、level・messageラベルを省略できる
logger.info('Loading Redirect Function');
loggerWithNotice.error('error message')

// logger.error, warning, info, debug の4段階で出力が可能

参考

TypeScriptでロギングするためにwinstonを導入してみる
https://qiita.com/18kondo/items/3d5738a1c2eacd83d4f4

winston
https://openbase.io/js/winston

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