Backend/NodeJS
[winston] How to log as daily rotate file
하우아유두잉
2019. 12. 20. 17:14
winston으로 날짜별 파일에 로그 기록하는 방법
사용 모듈: winston-daily-rotate-file
timestamp 커스텀: [node.js] - [winston] How to customize timestamp format. (to local timezone)
import moment from "moment";
const fecha = require("fecha");
const winston = require("winston");
require("winston-daily-rotate-file");
const format = winston.format;
const { combine, label, prettyPrint, colorize } = format;
// It's customized timestamp
const timestamp = format((info: any, opts: any = {}) => {
if (opts.format) {
info.timestamp = typeof opts.format === "function"
? opts.format()
: fecha.format(moment(), opts.format);
}
if (!info.timestamp) {
info.timestamp = moment().format().replace(/T/, " ").replace(/\+.+/, "");
}
if (opts.alias) {
info[opts.alias] = info.timestamp;
}
return info;
});
const tsFormat = () => (new Date()).toLocaleTimeString();
const transport = new (winston.transports.DailyRotateFile)({
filename: `[NAME]-%DATE%.log`,
datePattern: `YYYY-MM-DD-HH`,
zippedArchive: true,
maxSize: `20m`,
maxFiles: `14d`,
});
transport.on(`rotate`, function(oldFilename: string, newFilename: string) {
// do something fun
});
export const wstlogger = winston.createLogger({
format: combine(
label({ label: `LABEL` }),
timestamp(),
prettyPrint(),
colorize()
),
transports: [
transport,
new (winston.transports.Console)({
timestamp: tsFormat,
colorize: true
})
]
});
const TAG = `[LOGGER]`;
wstlogger.info(`${TAG} info message`);
wstlogger.warn(`${TAG} warn message`);
wstlogger.error(`${TAG} error message`);
코드를 실행시키면 콘솔에 아래와 같이 로그가 출력된다.
루트 디렉토리를 보면 .log 파일이 생성되었을 것이다.
정상적으로 로그가 기록된 것을 확인 할 수 있다.