NodeJS

How To Use Winston to Log Node.js Applications

lahuman 2019. 2. 6. 16:28
728x90

How To Use Winston to Log Node.js Applications

간단하게 설정만 작성하는 것으로 원본자료 How To Use Winston to Log Node.js Applications을 보세요.

var appRoot = require('app-root-path');
var winston = require('winston');

// define the custom settings for each transport (file, console)
var options = {
  file: {
    level: 'info',
    filename: `${appRoot}/logs/app.log`,
    handleExceptions: true,
    json: true,
    maxsize: 5242880, // 5MB
    maxFiles: 5,
    colorize: false,
  },
  console: {
    level: 'debug',
    handleExceptions: true,
    json: false,
    colorize: true,
  },
};

// instantiate a winston.createLogger with the settings defined above
var logger = winston.createLogger({
  transports: [
    new winston.transports.File(options.file),
    new winston.transports.Console(options.console)
  ],
  exitOnError: false, // do not exit on handled exceptions
});

// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
  write: function(message, encoding) {
    // use the 'info' log level so the output will be picked up by both transports (file and console)
    logger.info(message);
  },
};

module.exports = logger;

요렇게 설정만 해놓아도 기본으로 사용이 가능하다.

추가로 알게된 App Root Path Module 도 꽤 유용해보인다.

app의 root path를 제공하여 다음과 같이 사용할 수 있다.

#1 
var appRoot = require('app-root-path');
var myModule = require(appRoot + '/lib/my-module.js');

#2
var reqlib = require('app-root-path').require;
var myModule = reqlib('/lib/my-module.js');

#3
// In app.js
global.reqlib = require('app-root-path').require;
 
// In lib/module/component/subcomponent.js
var myModule = reqlib('/lib/my-module.js');

#4
var myModulePath = require('app-root-path').resolve('/lib/my-module.js');

좋은게 많은데 몰라서 못쓴다.

공부 많이 좀 해야겠다. 요즘 게을러져서 공부도 안하고 그냥 날로 먹을라고 한다.

참고 자료


728x90