winston console만 colorize()

broccoli·2021년 5월 12일
0

logging

목록 보기
3/4
post-thumbnail

winston을 사용하면서 console에만 colorize() 해야한다. 파일에 저장할 때도 colorize하게 되면 파일에 색관련 특수문자가 같이 찍히기 때문이다.

console에만 colorize하기

아래 예에서 consoleOpts옵션을 new winston.transports.Console(consoleOpts)에 적용해주면 된다.

const winston = require('winston')
const WinstonDaily = require('winston-daily-rotate-file')
const path = require('path')

const { combine, timestamp, printf, colorize } = winston.format

const logDir = 'logs'

const levels = {
  error: 0,
  warn: 1,
  info: 2,
  http: 3,
  debug: 4
}

const colors = {
  error: 'red',
  warn: 'yellow',
  info: 'green',
  http: 'magenta',
  debug: 'blue'
}
winston.addColors(colors)

const level = () => {
  const env = process.env.NODE_ENV || 'development'
  const isDevelopment = env === 'development'
  return isDevelopment ? 'debug' : 'http'
}

// Log Format
const logFormat = combine(
  timestamp({ format: 'YYYY-MM-DD HH:mm:ss:ms' }),
  printf((info) => {
    if (info.stack) {
      return `${info.timestamp} ${info.level}: ${info.message} \n Error Stack: ${info.stack}`
    }
    return `${info.timestamp} ${info.level}: ${info.message}`
  })
)

// 콘솔에 찍힐 때는 색깔을 구변해서 로깅해주자.
const consoleOpts = {
  handleExceptions: true,
  level: process.env.NODE_ENV === 'production' ? 'error' : 'debug',
  format: combine(
    colorize({ all: true }),
    timestamp({ format: 'YYYY-MM-DD HH:mm:ss:ms' })
  )
}

const transports = [
  // 콘솔로그찍을 때만 색넣자.
  new winston.transports.Console(consoleOpts),
  // error 레벨 로그를 저장할 파일 설정
  new WinstonDaily({
    level: 'error',
    datePattern: 'YYYY-MM-DD',
    dirname: path.join(__dirname, logDir, '/error'),
    filename: '%DATE%.error.log',
    maxFiles: 30,
    zippedArchive: true
  }),
  // 모든 레벨 로그를 저장할 파일 설정
  new WinstonDaily({
    level: 'debug',
    datePattern: 'YYYY-MM-DD',
    dirname: path.join(__dirname, logDir, '/all'),
    filename: '%DATE%.all.log',
    maxFiles: 7,
    zippedArchive: true
  })
]

const Logger = winston.createLogger({
  level: level(),
  levels,
  format: logFormat,
  transports
})

module.exports = Logger

참고링크

profile
🌃브로콜리한 개발자🌟

0개의 댓글