Nodejs로 Express 서버를 만드는데 Debugging 용도로 console.log를 사용했었다. 그냥 이게 편하고 익숙해서...ㅎ
하지만 Project를 실제 수행하다보면 서버의 동작을 파악하거나 오류를 찾아야 할때 로그파일을 뒤져보는 것이 가장 1순위일 것이다.
Nodejs로 Log를 남기고 관리하는 모듈은 많이 있다. morgan, winston 등등...
두가지를 함께 사용하는 것도 가능하다.
하지만 여기서는 가장 인기 있는 winston 라이브러리를 사용하는 방법을 간단하게 소개한다.
01. npm으로 설치하기
1 | npm install --save winston | cs |
02. winston.js 작성
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | const appRoot = require('app-root-path'); // app root 경로를 가져오는 lib const winston = require('winston'); // winston lib const process = require('process'); const { combine, timestamp, label, printf } = winston.format; const myFormat = printf(({ level, message, label, timestamp }) => { return `${timestamp} [${label}] ${level}: ${message}`; // log 출력 포맷 정의 }); const options = { // log파일 file: { level: 'info', filename: `${appRoot}/logs/winston-test.log`, // 로그파일을 남길 경로 handleExceptions: true, json: false, maxsize: 5242880, // 5MB maxFiles: 5, colorize: false, format: combine( label({ label: 'winston-test' }), timestamp(), myFormat // log 출력 포맷 ) }, // 개발 시 console에 출력 console: { level: 'debug', handleExceptions: true, json: false, // 로그형태를 json으로도 뽑을 수 있다. colorize: true, format: combine( label({ label: 'nba_express' }), timestamp(), myFormat ) } } let logger = new winston.createLogger({ transports: [ new winston.transports.File(options.file) // 중요! 위에서 선언한 option으로 로그 파일 관리 모듈 transport ], exitOnError: false, }); if(process.env.NODE_ENV !== 'production'){ logger.add(new winston.transports.Console(options.console)) // 개발 시 console로도 출력 } module.exports = logger; | cs |
02. app.js에 logger 추가하기
1 2 3 4 5 6 7 8 9 10 11 | const express = require('express'); const bodyParser = require('body-parser') const app = express(); const api = require('./routes/index'); const winston = require('./config/winston') app.use(bodyParser.json()); app.use('/api', api); const port = process.env.PORT || 3001; app.listen(port, () => winston.info(`Listening on port ${port}...`)); | cs |
위에서 만든 모듈을 임포트하고
winston.info(message) 형식으로 사용하면 된다.(간단ㅎㅎ)
로그 레벨을 아래와 같은 종류가 있다.
{ emerg: 0, alert: 1, crit: 2, error: 3, warning: 4, notice: 5, info: 6, debug: 7 }
03. app 실행
1 2 | PS C:\node-project\winston-test> node app.js 2019-02-19T14:48:48.785Z [winston-test] info: Listening on port 3001... | cs |
console에 log가 위에서 정의한 format으로 출력된 것을 확인 할 수 있다.
또한 로그파일도 생성되어 로그가 쓰여진것을 확인 할 수 있다.
winston-test/logs/winston-test.log
1 2 | 2019-02-19T14:48:48.784Z [winston-test] info: Listening on port 3001... | cs |
04. morgan과 함께 사용
1 2 | npm install --save morgan | cs |
winston-test/config/winston.js 에 아래 코드 추가
1 2 3 4 5 6 7 8 | ... logger.stream = { write: function(message, encoding) { logger.info(message); // 단순히 message를 default 포맷으로 출력 }, }; module.exports = logger | cs |
winston-test/app.js에 미들웨어 추가
1 2 3 4 | ... app.use(bodyParser.json()); app.use(morgan('combined', {stream: winston.stream})); // morgan http 로그 미들웨어 추가 ... | cs |
app 실행 후, http 요청을 보내보자.
1 | 2019-02-19T14:55:45.138Z [winston-test] info: ::ffff:127.0.0.1 - - [19/Feb/2019:14:55:45 +0000] "POST /api/hello HTTP/1.1" 400 65 "-" "PostmanRuntime/7.6.0" | cs |
로그의 message에 morgan이 뱉은 로그를 확인 할 수 있다.
실제 결합하여 사용하려면 log format을 맞출 필요가 있어보인다...(@@)
'개발 이야기 > NodeJS' 카테고리의 다른 글
NodeJS 콜백을 사용한 비동기 제어 흐름 패턴 (0) | 2019.03.09 |
---|---|
NodeJS 동작 방식과 개념 정리 (0) | 2019.03.02 |
NodeJS validate로 요청 데이터 검사 (0) | 2019.02.11 |
NodeJS Express 간단한 서버 만들기 (0) | 2019.02.11 |
우분투에 Nodejs설치 하기 (0) | 2018.07.28 |