備忘録

備忘録

Node.js用のロガー(winston)の使い方

Ⅰ. はじめに

タイトルの通り「Node.js用のロガー(winston)の使い方」です。

Ⅱ. やり方

1. winstonをインストールする
npm i winston
2. サンプルプログラムを書く
const winston = require('winston')
const moment = require('moment')

const myFormat = winston.format.printf(x => `${moment().format('YYYY-MM-DD HH:mm:ss')} [${x.level}]: ${x.message}`)

const logger = winston.createLogger({
  level: 'silly',
  transports: [
    new winston.transports.Console({ format: myFormat }),
    new winston.transports.File({ filename: 'Log.txt', format: myFormat })
  ]
})

logger.error('helloworld')
logger.warn('helloworld')
logger.info('helloworld')
logger.http('helloworld')
logger.verbose('helloworld')
logger.debug('helloworld')
logger.silly('helloworld')

実行結果

2020-12-13 02:40:45 [error]: helloworld
2020-12-13 02:40:45 [warn]: helloworld
2020-12-13 02:40:45 [info]: helloworld
2020-12-13 02:40:45 [http]: helloworld
2020-12-13 02:40:45 [verbose]: helloworld
2020-12-13 02:40:45 [debug]: helloworld
2020-12-13 02:40:45 [silly]: helloworld