Notice
Recent Posts
Recent Comments
Link
스토리지
[07.04] Node.js - Winston으로 logging하기 본문
Node.js를 사용하며 서버 프로그래밍을 하던 중 console.log의 한계점을 느꼈다.
1. 사람이 24시간 console창을 보고 있지 않는다.
2. 과거의 log를 확인하기 쉽지않다.
이러한 이유로 찾아보니 winston이라는 npm 패키지가 있다. 자꾸 stone이라고 적는다.
https://www.npmjs.com/package/winston
winston
A logger for just about everything.
www.npmjs.com
https://www.npmjs.com/package/winston-daily-rotate-file
winston-daily-rotate-file
A transport for winston which logs to a rotating file each day.
www.npmjs.com
winston-daily-rotate-file은 날짜별로 log를 정리해준다. 굉장히 편하다.
1. 먼저 winston과 winston-daily-rotate-file을 install해준다.
2. config라는 폴더 아래에 js파일 하나와 logs폴더 하나를 생성해줍니다.
3. 생성된 js파일에 다음과 같이 기록합니다.
const winston = require("winston");
const winstonDaily = require("winston-daily-rotate-file");
const appRoot = require("app-root-path");
const logDir = `${appRoot}/logs`;
const { combine, timestamp, label, printf } = winston.format;
const logFormat = printf(({ level, message, label, timestamp }) => {
return `${timestamp} [${label}] ${level}: ${message}`;
});
const logger = winston.createLogger({
format: combine(
label({
label: "System Name",
}),
timestamp({
format: "YYYY-MM-DD HH:mm:ss",
}),
logFormat
),
transports: [
new winstonDaily({
level: "info",
datePattern: "YYYY-MM-DD",
dirname: logDir,
maxFiles: 30,
filename: `%DATE%.log`,
}),
new winstonDaily({
level: "error",
datePattern: "YYYY-MM-DD",
dirname: logDir,
maxFiles: 30,
filename: `%DATE%.error.log`,
zippedArchive: true,
}),
],
exceptionHandlers: [
new winstonDaily({
level: "error",
datePattern: "YYYY-MM-DD",
dirname: logDir,
filename: `%DATE%.exception.log`,
maxFiles: 30,
zippedArchive: true,
}),
],
});
module.exports = logger;
아래의 것은 형식을 지정하는 곳이고 const logFormat 이 부분이 출력되는 방법을 지정하는 곳입니다.
여기를 수정해서 자신이 원하는 로그형식을 만들 수 있습니다.
const log = require("../config/logger");
log.info(userId + " connected");
로그를 출력할 때에는 require로 아까만든 js파일을 불러온 뒤에,
info 메서드를 불러오면 완성됩니다.
'개발일지' 카테고리의 다른 글
[07.08] Google Analytics (0) | 2021.07.08 |
---|---|
[07.07] 코루틴을 사용하지 않고 이미지에 Fade In / Fade Out 효과 넣기 (0) | 2021.07.07 |
[06.30] Firebase 사용하기 (0) | 2021.06.30 |
[06.14] AWS EC2를 이용해서 웹서버 배포하기 - 03 (0) | 2021.06.14 |
[06.14] AWS EC2를 이용해서 웹서버 배포하기 - 02 (0) | 2021.06.14 |
Comments