nodejs200제 - 159. winston 모듈(로그파일)

prana·2022년 6월 27일
1

ㅎ ㅎ.ㅎㅎ 크롬 창 모두 닫기 하다가 글이 날라가서 ㅎ ㅎ ㅎ.,ㅎ 다시 쓴다

사건의 발단 :

winston 모듈 적용하는 데까지는 하였으나, timestamp와 color 적용이 되지 않았다. 그리고 자세히 이해도 못했음.
1. winston timestamp 뜨지 않음, 안 됨
2. winston colorize 적용 문제

기존 코드

const winston = require('winston');
const winstonDaily = require('winston-daily-rotate-file');
const moment = require('moment');

const tsFormat = () => {
    return moment().format('YYYY-MM-DD HH:mm:ss.SSS ZZ');
}

const logger = winston.createLogger({
    transports: [
      new winston.transports.Console({
        timestamp: tsFormat,
        colorize: true,
        showlevel: true,
        level: 'debug',
      }),
      new winstonDaily({ //매일 새로운 파일에 로그를 기록하도록 설정

        level: 'info',
        filename: './node200_project/Log/logs',
        timestamp: tsFormat,
        datePattern: 'YYYY-MM-DD',
        showlevel: true,
        maxsize: 1000000, //로그 파일 크기가 10MB가 넘어가면 새로운 파일을 만듦
        maxFiles: 5, //최대 5개까지 가능
      }),

    ],
    exceptionHandlers: [
     new winstonDaily({
        level: 'info',
        filename: './node200_project/Log/exception',
        timestamp: tsFormat,
        datePattern: 'YYYY-MM-DD',
        showlevel: true,
        maxsize: 1000000,
        maxFiles: 5,

      }),
      new winston.transports.Console({
        timestamp: tsFormat,
        colorize: true,
        showlevel: true,
        level: 'debug',
      }),
    ],
  });

  logger.info('인포 로깅');
  logger.error('에러 로깅');

tip1. 파일명은 logs.2022-~ 날짜 로 설정을 해두었었는데, %DATE% 를 넣으면 쉽게 가능하다.

https://github.com/winstonjs
filename: Filename to be used to log to. This filename can include the %DATE% placeholder which will include the formatted datePattern at that point in the filename. (default: 'winston.log.%DATE%')

문제1: timestamp 안나옴

문제1 해결: 속성에 없다. 즉, timestamp: tsFormat가 소용이 없었다.

https://github.com/winstonjs
사이트를 참고하여 transform 및 combine() 을 활용했고..

온갖 것들을 다 넣어봤다 ㅋㅋㅋ 그리고 깃헙에서 logform 도 언급되길래

npm install logform --save

하여 추가로 넣어주었다.

문제2: 색상 적용이 안되네..?

문제2해결: 알고보니 console.log에서 출력되는 javascript의 형식이 ANSI이었다.

그래서 맨 위 터미널 -> 새 터미널을 열어

cat Log/logs.2022-06-27-15 명령어로 실행

그랬더니...!!

cat 명령어로 파일 읽기 를 시도해봤더니 ㅎㅎ 터미널 상에선 문제없이 잘 출력되고 있었던 것. 형식 잡아준 부분은 위에 logFormat 에 맞춰서 했다.

현재 코드

const winston = require('winston');
const winstonDaily = require('winston-daily-rotate-file');
// const moment = require('moment');
const { format } = require('logform');
const { combine, timestamp, json, colorize, label, prettyPrint, simple, printf, align } = format;

// Define log format
const logFormat = printf(({level, message, label, timestamp})=>{
  return `${timestamp} [${label}] ${level}: ${message}`; 
});

const jsonWithTimestamp = combine(
  json(),
  colorize({all:true}),
  label({label: 'label test!!'}),
  simple(),
  timestamp({ format: ' YYYY-MM-DD HH:MM:SS ||' }),
  align(),
  prettyPrint(),
  logFormat
);


const logger = winston.createLogger({
  transports: [
      new winston.transports.Console({
        colorize: true,
        showlevel: true,
        level: 'debug',
        handleExceptions: true,
        zippedArchive: true,
        format: jsonWithTimestamp,
        prettyPrint: true

      }),
      new winstonDaily({ //매일 새로운 파일에 로그를 기록하도록 설정
        level: 'info',
        filename: './node200_project/Log/logs',
        datePattern: 'YYYY-MM-DD-HH',
        showlevel: true,
        maxsize: 1000000, //로그 파일 크기가 10MB가 넘어가면 새로운 파일을 만듦
        maxFiles: 5, //최대 5개까지 가능
        zippedArchive: true,
        format: jsonWithTimestamp, 
      }),
  
    ],
    exceptionHandlers: [
     new winstonDaily({
        level: 'info',
        filename: './node200_project/Log/exception',
        datePattern: 'YYYY-MM-DD-HH',
        showlevel: true,
        maxsize: 1000000,
        maxFiles: 5,
        zippedArchive: true,
        format: jsonWithTimestamp,
      
      }),
      new winston.transports.Console({
        colorize: true,
        showlevel: true,
        level: 'debug',
        handleExceptions: true,
        zippedArchive: true,
        format: jsonWithTimestamp,
      }),
    ],
  });

module.exports = logger;
  
logger.info('인포 로깅');
logger.error('에러 로깅');

오늘 하루를 거의 다 날렸..^^지만 뿌듯하다!

profile
안녕하세요!!

0개의 댓글