| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
Tags
- elasticsearch
- nodejs
- java8
- node
- jface
- JPA
- 알고리즘
- effective
- Spring
- 인터페이스
- 엘라스틱서치
- 후기
- 독후감
- kibana
- Git
- java
- 자바스크립트
- 백준
- 이펙티브
- Web
- 리뷰
- javascript
- Spring Boot
- 맛집
- 자바
- MySQL
- RCP
- error
- 스프링
- boot
Archives
- Today
- Total
wedul
node.js에서 winston.js를 이용하여 로그 남겨보기. 본문
반응형
node.js에서 로그를 남기기 위해 사용되는 logger중 대표적인게 winston이라고 한다.
winston을 이용하여 간단하게 logger를 만들고 모든 동작에 대해 로그를 파일과 콘솔에 찍어보자.
winston 설치
1 | npm i winston —save | cs |
logger 생성
https://github.com/winstonjs/winston
위에 github에 나와있는 예제를 사용하여 그대로 logger를 만들어보자.
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 | #logger.js /** * Created by wedul on 2018. 8. 30. */ 'use strict'; const winston = require('winston'); class Logger { create() { // logger 파일 생성 const logger = winston.createLogger({ level: 'info', // log level format: winston.format.json(), transports: [ // // - Write to all logs with level `info` and below to `combined.log` // - Write all logs error (and below) to `error.log`. // 문서에서 확인해보면 더 많은 설정을 볼 수있다. // 파일 저장 로그 설정 (error log 위치) new winston.transports.File({ filename: 'error.log', level: 'error', prettyPrint: true }), // 파일 저장 로그 설정 (info log 설정) new winston.transports.File({ filename: 'info.log', prettyPrint: true }) ], colorize: true, humanReadableUnhandledException: true }); // 운영중이지 않을 경우 콘솔에 출력 추가 if (process.env.NODE_ENV !== 'production') { logger.add(new winston.transports.Console({ format: winston.format.simple() })); } return logger; } }; module.exports = new Logger(); | cs |
미들웨어 생성
모든 request와 response 사이에서 로그를 찍기위해서 간단한 미들웨어를 하나 만들자.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | ##logger-cathcer.js /** * Created by we on 2018. 8. 30. */ 'use strict'; module.exports = () => { return (req, rep, next) => { loggerFactory.info(‘Occupy Access Log’); // 미들웨어나 router 콜백에서 next 또는 response에 대한 응답을 생략하면 클라이언트가 계속 대기하게 되므로 꼭 잊지 말 것. next(); } }; | cs |
app.js에 미들웨어 설정
생성된 미들웨어를 정의하고 실행시켜보자.
1 2 3 4 5 | const loggerCatcher = require('./lib/middle/loggerCatcher'); // app.js global.loggerFactory = require('./lib/logger').create(); app.use(loggerCatcher()); | cs |
이벤트가 발생할때마다 로그가 찍히는것을 확인할 수 있다.
그리고 logger를 만들때 설정했었던 log파일도 생긴것을 확인할 수 있다.
반응형
'web > node.js' 카테고리의 다른 글
| router 경로 enumset 처럼 받는 방법과 테스트 사이트 (1) | 2018.10.05 |
|---|---|
| node.js에 swagger 적용 (4) | 2018.10.05 |
| 테스트 모듈 Assert 정리 (0) | 2018.10.05 |
| node.js express 모듈 - router (0) | 2018.10.05 |
| node.js에서 NODE_ENV를 사용하여 개발, 운영 환경 구분하기. (0) | 2018.10.04 |