반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

타닥타닥 민타쿠

Nodejs 파일명, 라인 나오게 로깅하기 (tracer 모듈) 본문

개발/Nodejs

Nodejs 파일명, 라인 나오게 로깅하기 (tracer 모듈)

민타쿠 2021. 8. 24. 20:29
반응형

Nodejs 에서 로깅 모듈로 유명한 winston 모듈은 성능 등의 이슈로 추적(tracing) 기능을 지원하지 않는다고 한다.
일부 유저들이 winston 을 쓰면서 파일명, 라인(몇째 줄인지)까지 나오게 하는 시도들이 있는 것 같지만,
불안정하고 성능이 좋지 못하다는 공식 입장을 보고도 그러한 방법을 써볼 필요는 없는 것 같다.

따라서, tracer 라는 편리한 모듈을 써서 쉽고 간편하게 파일명과 라인 출력을 해보았다.

  1. npm install tracer
    프로젝트 경로에서 명령어를 통해 모듈 설치
  2. tracer.js
    var fs = require('fs');
    
    var logger = require('tracer').colorConsole({
      transport: function(data) {
        console.log(data.output);
        // logs 폴더에 로그 파일을 생성할 것이므로 폴더를 미리 만들어 놓아야 한다!
        fs.appendFile('logs/'+getTodayFormat()+'.log', data.rawoutput + '\n', err => {
          if (err) throw err
        });
      }
    });
    
    function getTodayFormat() {
      let today = new Date();
    
      let year = today.getFullYear(); // 년도
      let month = today.getMonth() + 1;  // 월
      let date = today.getDate();  // 날짜
      // let day = today.getDay();  // 요일
    
      let format = year + '-' + (((month+'').length === 1)?'0':'')+month + '-' + (((date+'').length === 1)?'0':'')+date; // ex) 2021-08-24
    
      return format;
    }
    
    module.exports = logger;​


  3. app.js
    const express = require('express');
    const app = express();
    
    const logger = require('./pages/assets/js/tracer'); // tracer.js
    
    // 로컬 변수로 사용
    app.use(function(req, res, next) {
      res.locals.logger = logger;
      next();
    });​
  4. cognito.js (router)
    const express = require('express');
    const router = express.Router();
    
    router.get('/login', function(req,res){
      res.locals.logger.error('GET /login !?!?!');
      res.render('login');
    });​
  5. 로그 출력 확인
    - 콘솔
    tracer 모듈로 로깅된 콘솔 로그
    - 파일
    tracer 모듈로 생성된 로그 파일
    tracer 모듈로 로깅된 로그 파일 내용
    파일명은 위 format 에서 직접 설정해주었고
    날짜, 시간, 로그 레벨, 파일명, 라인, 로깅 내용까지 잘 출력 및 저장되었다.

참고로 로그 레벨은
log, trace, debug, info, warn, error 가 있고, 세부적인 설정방법은 아래 모듈참조페이지 링크를 통해서 알 수 있다.
모듈참조페이지

 

GitHub - baryon/tracer: A powerful and customizable logging library for node.js

A powerful and customizable logging library for node.js - GitHub - baryon/tracer: A powerful and customizable logging library for node.js

github.com

 

반응형
Comments