[node.js] winston version 3기준 node.js 로깅 설정(local timestamp 적용)

설명

  • winston 은 node.js 에서 사용하는 대표적인 logging 모듈이다.

  • 기본 형태로 logging 시 timestamp 가 기록되지 않으며,

    Local time 으로 지역 시간대 적용을 위해서 별도의 format 정의가 필요하다.

  • 아래 코드 예제를 통해서 로깅 파일 생성 및 지역 시간(서울) 기준으로 로깅이 가능하다.

실행 코드

const winston = require('winston')

const moment = require('moment-timezone')

const { createLogger, format, transports } = require('winston');
const { combine, timestamp, label, printf } = format;

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

const appendTimestamp = format((info, opts) => {
  if(opts.tz)
    info.timestamp = moment().tz(opts.tz).format();
  return info;
});

// Config Log
const logger = winston.createLogger({
  format: combine(
      label({ label: 'gather_gluster_info' }),
      appendTimestamp({ tz: 'Asia/Seoul' }),
      myFormat
  ),
  defaultMeta: { service: 'user-service' },
  transports: [
    //
    // - Write to all logs with level `info` and below to `combined.log`
    // - Write all logs error (and below) to `error.log`.
    new winston.transports.File({ filename: 'test.log' })
  ]
});

logger.log('error', "TT")


다른 카테고리의 글 목록

node.js 카테고리의 포스트를 톺아봅니다