Winston
- Node.js에서 Log를 효율적으로 관리할 수 있도록 하는 모듈
winston 로그 레벨
- error(빨강) > warn(노랑) > info(초록) > http(초록) > verbose(하늘) > debug(파랑) > silly(보라)
winston.format
- 기본 포맷은 JSON이지만 combine을 통해 여러 형식을 혼합해서 지정할 수 있음
- timestamp = 로그 발생 시점 (날짜 형식 지정)
- label = 로그가 발생한 어플리케이션 이름 지정
- level = 로그 레벨
- message = 로그 내용
- printf = 출력 형태 지정
※ level과 message는 자동으로 지정됨
const winston = require('winston');
const winstonDaily = require('winston-daily-rotate-file');
const process = require('process');
const { combine, timestamp, label, printf } = winston.format;
// process.cwd() = 루트 경로 (C:)
const logDir = `${process.cwd()}/logs`;
// log 출력 포맷 정의 함수
const logFormat = printf(({ level, message, label, timestamp }) => {
return `${timestamp} [${label}] ${level}: ${message}`; // 날짜 [시스템이름] 로그레벨: 메세지
});
winston-daily-rotate-file (winstonDaily)
- 로그 파일을 관리해주는 모듈
- 하루 단위로 새 로그 파일 생성
- 날짜별로 로그 파일을 관리할 수 있도록 구분
- winstonDaily 객체 => 어떤 레벨의 로그를 저장할때 어떤 형식으로 몇일동안 보관할지를 상세히 설정
const logger = winston.createLogger({
// 로그 출력 형식 정의
format: combine(
timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), // 날짜 데이터 형식
label({ label: 'Winston 연습 어플리케이션' }), // 어플리케이션 이름
logFormat, // log 출력 포맷
),
// 로그 출력 형식 정의 (레벨별 설정)
transports: [
// info 레벨 로그를 저장할 파일 설정 (info: 2 보다 높은 error: 0 와 warn: 1 로그들도 자동 포함해서 저장)
new winstonDaily({
level: 'info', // 레벨 지정
datePattern: 'YYYY-MM-DD', // 파일 날짜 형식
dirname: logDir + '/info', // 파일 경로
filename: `%DATE%.log`, // 파일 이름
maxFiles: 30, // 최근 30일치 로그 파일을 남김
zippedArchive: true, // 아카이브된 로그 파일을 gzip으로 압축할지 여부
}),
// error 레벨 로그를 저장할 파일 설정 (info에 자동 포함되지만 일부러 따로 빼서 설정)
new winstonDaily({
level: 'error',
datePattern: 'YYYY-MM-DD',
dirname: logDir + '/error',
filename: `%DATE%.error.log`,
maxFiles: 30,
zippedArchive: true,
}),
],
// uncaughtException 발생 시 설정
// uncaughtException = 예측하지 못한 에러들을 하나로 모은 것
exceptionHandlers: [
new winstonDaily({
level: 'error',
datePattern: 'YYYY-MM-DD',
dirname: logDir,
filename: `%DATE%.exception.log`,
maxFiles: 30,
zippedArchive: true,
}),
],
});
process.env.NODE_DEV
- production(배포) / development(개발) 모드 설정
- cross-env 모듈 설치(Windows에서 process.env.NODE_ENV 설정에 필요) 후 package.json의 scripts 부분에서 설정
"scripts": {
"start": "cross-env NODE_ENV=production PORT=80 node server", // NODE_ENV를 production으로 설정 + 포트 80번
"dev": "nodemon server",
"test": "jest"
}
※ winston.format.colorize() = 색깔을 넣도록 설정
※ winston.format.simple() = ${info.level}: ${info.message} JSON.stringify({ ...rest }) 포맷으로 출력
// 개발 환경(development)일 경우 화면에서 바로 로그를 찍도록 설정 (로그 파일은 여전히 생성됨)
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 })` 포맷으로 출력
),
}),
);
}
'Node.js' 카테고리의 다른 글
Node.js 클러스터 (0) | 2023.08.28 |
---|---|
Node.js 정의 및 장단점 (0) | 2023.06.06 |
Node.js Swagger 적용 (0) | 2023.06.03 |
Socket.io (0) | 2023.05.31 |
Nodemon/PM2 (0) | 2023.05.30 |
댓글