본문 바로가기
Learning

document, winston.js

by zsgg 2020. 1. 21.

winston

간단하고 범용적인 로깅라이브러지를 지향함

Logging

const levels = { 
  error: 0,
  warn: 1,
  info: 2,
  http: 3,
  verbose: 4,
  debug: 5,
  silly: 6
};

중요도 순서로 내림차순 된다

const logger = winston.createLogger({
  transports: [
    new winston.transports.Console(),
  ]
});

const childLogger = logger.child({ requestId: '451' });

메타데이터를 상속받는 새로운 logger를 만들 수 있음

const logger = winston.createLogger({
  level: 'info',
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

//
// Replaces the previous transports with those in the
// new configuration wholesale.
//
const DailyRotateFile = require('winston-daily-rotate-file');
logger.configure({
  level: 'verbose',
  transports: [
    new DailyRotateFile(opts)
  ]
});

이렇게 정의해서 쓰는걸 권장한다

Formats

const logger = createLogger({
  format: combine(
    label({ label: 'right meow!' }),
    timestamp(),
    prettyPrint()
  ),
  transports: [new transports.Console()]
})

여러 조합을 섞어서 사용할 수 있다

const { createLogger, format, transports } = require('winston');

// Ignore log messages if they have { private: true }
const ignorePrivate = format((info, opts) => {
  if (info.private) { return false; }
  return info;
});

const logger = createLogger({
  format: format.combine(
    ignorePrivate(),
    format.json()
  ),
  transports: [new transports.Console()]
});

// Outputs: {"level":"error","message":"Public error to share"}
logger.log({
  level: 'error',
  message: 'Public error to share'
});

// Messages with { private: true } will not be written when logged.
logger.log({
  private: true,
  level: 'error',
  message: 'This is super secret - hide it.'
});

필터 기능이 있다

Profiling

 const profiler = logger.startTimer();
 setTimeout(function () {
   profiler.done({ message: 'Logging message' });
 }, 1000);

 logger.profile('test', { level: 'debug' });

오 시간비교도 가능한건가?

적용해본 코드

import {resolve} from 'path';
import {createLogger, format, transports} from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';

const fileBase = process.env.LOG_FILE_BASE as string || resolve(__dirname, '..', '../log');
const commonFormat = format.combine(
    format.colorize({all: true}),
    format.timestamp({
        format: 'YYYY-MM-DD HH:mm:ss',
    }),
    format.printf(
        info => {
            const {
                timestamp, level, message, ...args
            } = info;
            const objString = Object.keys(args).length ? JSON.stringify(args, null, 2) : '';
            return `${timestamp} [${level}] - ${message} / ${objString}`;
        },
    ),
    format.splat(),
);
const logger = createLogger({
    level: 'silly',
    transports: [
        new DailyRotateFile({
            filename: `${process.env.NODE_ENV}-%DATE%.log`,
            dirname: resolve(`${fileBase}`),
            datePattern: 'YYYY-MM-DD',
            zippedArchive: false,
            maxSize: '50m',
            maxFiles: '30d',
        }),
        new DailyRotateFile({
            filename: `${process.env.NODE_ENV}-%DATE%.error.log`,
            datePattern: 'YYYY-MM-DD',
            dirname: resolve(`${fileBase}`),
            format: format.combine(commonFormat, format.errors({stack: true})),
            level: 'error',
        }),
        new transports.Console({
            handleExceptions: true,
        }),
    ],
    exceptionHandlers: [
        new DailyRotateFile({
            datePattern: 'YYYY-MM-DD',
            filename: `${process.env.NODE_ENV}-%DATE%.exceptions.log`,
            dirname: resolve(`${fileBase}`),
            handleExceptions: true,
        }),
    ],
    format: commonFormat,
});

export default logger;

'Learning' 카테고리의 다른 글

인사이드 자바스크립트  (0) 2020.01.23
document, Express.js  (0) 2020.01.21
성공과 실패를 결정하는 1%의 네트워크 원리  (0) 2020.01.21
생각을 넓혀주는 독서법  (0) 2020.01.19
서평 쓰는 법  (0) 2020.01.19

댓글