[node.js] winston에서 한국 시간대 출력하기

Donghun Seol·2022년 11월 16일
0

winston

실제 서버를 운영할때 console.log와 console.error를 대체해주는 모듈이다. 로그를 파일이나 db에 원하는 형식대로 저장할 수 있으므로 서버가 종료되더라도 에러메시지들이 보존된다.

일반적으로 console.loglogger.info로, console.errorlogger.error로 대체해서 활용한다.

아래의 logger.js 파일에서 정의한 logger 모듈을 app.js에서 require해서 사용하면된다.

환경변수에 따라 개발환경에서는 console에 출력하는 transport를 추가해준다.

timestamp

서버가 종료되어 에러메시지를 확인해야 할때는 해당 에러가 언제 발생했는지 파악하는 것이 중요하다. winston의 format중 timestamp를 활용하면 에러메시지와 함께 timestamp를 출력할 수 있다.

한국시간

추가 설정없이 출력되는 timestamp는 utc기준이므로 실제 활용하기는 불편하다. 따라서 한국 시간대로 변경해서 출력, 기록하는 방법을 찾아봤다.
stackOverflow 레퍼런스

아래의 코드에서 koreanTime이라는 함수를 정의해서 format안에 넣어줌으로써 간단히 해결되었다.

콘솔에 출력되는 transport에서는 UTC timestamp가 그대로 출력되고, 'combined.log'파일에선 koreanTime이 적용된 timestamp가 저장되는 것을 확인할 수 있다.

logger.js

const { createLogger, format, transports } = require('winston');

const koreanTime = () => new Date().toLocaleString('en-US', {
  timeZone: 'Asia/Seoul',
});

const logger = createLogger({
  level: 'info',
  format: format.combine(format.json(), format.timestamp()),
  transports: [
    new transports.File({
      filename: 'combined.log',
      format: format.combine(format.timestamp(
        { format: koreanTime },
      ), format.json()),
    }),
    new transports.File({ filename: 'error.log', level: 'error' }),
  ],
});

if (process.env.NODE_ENV !== 'production') {
  logger.add(new transports.Console({ format: format.combine(format.timestamp(), format.json()) }));
}

module.exports = logger;
profile
I'm going from failure to failure without losing enthusiasm

0개의 댓글