-
[NodeJs] winston모듈을 사용하여 로그 저장하기프레임워크/NodeJs 2020. 10. 20. 21:29
먼저 아래 두개의 모듈을 설치해줍니다.
$ npm install winston $ npm install winston-daily-rotate-file
winston-daily-rotate-file : 날짜에 따라 자동으로 파일이 생성되며 로그가 쌓일 수 있도록 도와주는 모듈
제가 사용한 버전은 아래와 같습니다.
"winston": "^3.3.3" "winston-daily-rotate-file": "^4.5.0"
저는 logSave.js 라는 파일을 만든 후, 해당 파일을 모듈화하여 사용하였습니다.
const winston = require('winston'); require('winston-daily-rotate-file'); // level 종류 // error:0 , warn:1, info:2, http:3, verbose:4, debug:5, silly:6 // 기본 로그 저장방식이 json으로 되어있어 일반적인 텍스트 형식으로 로그를 저장하도록 변경 const myFormat = winston.format.printf(({ level, message, timestamp }) => { return `${timestamp} [${level}] ${message}`; }); // transport 설정 (날짜별로 저장) const transport = new (winston.transports.DailyRotateFile)({ filename: '../bin/log/application-%DATE%.log', datePattern: 'YYYY-MM-DD', zippedArchive: true, maxSize: '20m', maxFiles: '14d', format: winston.format.combine( winston.format.timestamp(), myFormat ) }); module.exports = winston.createLogger({ transports: [ transport ] }); //logger.info('Hello World!');
transport의 옵션을 수정하여 자유롭게 사용하시면 됩니다.
아래 이미지는 transport의 옵션 내용입니다.
출처 : https://github.com/winstonjs/winston/blob/master/docs/transports.md#file-transport 위 코드를 작성하여 다른 파일에서 모듈을 불러와 실행합니다.
const logger = require('../bin/logSave'); //위에서 작성한 모듈 logger.info("테스트"); logger.error("rows is not defined");
출력된 결과물
2020-10-20T10:03:14.181Z [info] 테스트 2020-10-20T11:22:08.424Z [error] rows is not defined
생성된 파일명 : application-2020-10-20.log
// 2020-10-23 추가
try catch한 error exception 메세지도 함께 저장하기위해 수정을 진행함
const logger = require('../bin/logSave'); //위에서 작성한 모듈 try{ } catch(err) { logger.error("exception내용 ("+ err +")"); }
출력된 결과물
2020-10-23T07:02:44.732Z [error] exception내용 (Error: Request failed with status code 404) 2020-10-23T07:03:02.020Z [error] exception내용 (Error: Request failed with status code 404)
생성된 파일명 : application-2020-10-23.log
// 2020-10-30 추가
error 메세지에 자세한 정보 [console.log(err)했을 때 뱉는 에러메세지]를 추가로 저장하자
const logger = require('../bin/logSave'); //위에서 작성한 모듈 try{ } catch(err) { logger.error(err.stack); }
출력된 결과물
2020-10-30 01:08:27 [error] [index.js] errorError: Incorrect integer value: 'null' for column 'column_name' at row 1 at PromisePoolConnection.query (C:\git\node_modules\mysql2\promise.js:92:22) at parsing (C:\git\gmarket-crawling-js\index.js:165:32) at runMicrotasks (<anonymous>) at processTicksAndRejections (internal/process/task_queues.js:94:5) at async crawler (C:\git\index.js:233:13)
생성된 파일명 : application-2020-10-30.log
ps. 포스트 내용에는 없지만 진행한 작업
1. 날짜 포맷 변경 (우리가 흔히 보는 형식으로 볼 수 있도록)
2. 위 출력된 결과물의 [index.js] 내용처럼 어떤 파일에서 로그를 불러 저장했는지 볼 수 있는 코드 추가
'프레임워크 > NodeJs' 카테고리의 다른 글
[NodeJs] localhost가 실행되었는데 127.0.0.1 에 접속되지 않는 경우 (0) 2022.11.05 [NodeJs] Exit status 3221225477 발생. 및 해결 (0) 2022.10.08 [NodeJs] 채팅 서버 만들어서 실행하기 (0) 2022.05.29 [NodeJs] tosource - console창에 [Function]이 출력 될 때 사용하는 라이브러리 (0) 2021.03.06 [NodeJs] puppeteer - EPERM error 발생 (0) 2021.02.21