반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

타닥타닥 민타쿠

Nodejs 로그 저장하기(winston 모듈) 본문

개발/Nodejs

Nodejs 로그 저장하기(winston 모듈)

민타쿠 2021. 7. 31. 00:02
반응형

로깅을 위해 Nodejs 에서 가장 많이 사용되는 winston 모듈을 적용 및 테스트하였다.

winston 모듈로 로깅하면 로그 레벨별로 색상을 구분하여 출력할 수 있으며,
레벨별, 날짜별로 저장하고 보관 기간 등 원하는 설정을 할 수가 있다.

winston 모듈 적용 방법

  1. npm install winston winston-daily-rotate-file
    프로젝트 경로에서 cmd로 winston 과 winston-daily-rotate-file 모듈 설치 명령어를 입력한다.

  2. winston.js 작성
    const winston = require('winston');
    const winstonDaily = require('winston-daily-rotate-file');
    
    const logDir = 'logs';  // 로그 파일 저장 경로 설정
    const { combine, timestamp, printf } = winston.format;
    
    // Define log format
    const logFormat = printf(info => {
      return `${info.timestamp} ${info.level}: ${info.message}`;
    });
    
    /*
     * Log Level
     * error: 0, warn: 1, info: 2, http: 3, verbose: 4, debug: 5, silly: 6
     */
    const logger = winston.createLogger({
      format: combine(
        timestamp({
          format: 'YYYY-MM-DD HH:mm:ss',
        }),
        logFormat,
      ),
      transports: [
        // info 레벨 로그를 저장할 파일 설정
        new winstonDaily({
          level: 'info',
          datePattern: 'YYYY-MM-DD',
          dirname: logDir,
          filename: `%DATE%.log`,
          maxFiles: 30,  // 30일치 로그 파일 저장
          zippedArchive: true, 
        }),
        // error 레벨 로그를 저장할 파일 설정
        new winstonDaily({
          level: 'error',
          datePattern: 'YYYY-MM-DD',
          dirname: logDir + '/error',  // error.log 파일은 error 폴더를 만들어 저장 
          filename: `%DATE%.error.log`,
          maxFiles: 30,
          zippedArchive: true,
        }),
      ],
    });
    
    // Production 환경이 아닌 경우(dev 등) 
    if (process.env.NODE_ENV !== 'production') {
      logger.add(new winston.transports.Console({
        format: winston.format.combine(
          winston.format.colorize(),  // 색깔 넣어서 출력
          winston.format.simple(),  // `${info.level}: ${info.message} JSON.stringify({ ...rest })` 포맷으로 출력
        )
      }));
    }
    
    module.exports = logger;


  3. 로거를 사용할 위치에서 import 하기
    const logger = require('./winston.js의 경로/winston');​


  4. 로깅하기
    logger.info('GET /index !');
    
    logger.error('Get index error occurred!');​


  5. 로그 확인
    winston 로그 저장 폴더
    텍스트 파일 및 폴더가 잘 생성된다.

 

반응형
Comments