node日誌庫winston

winston

node日誌庫,地址 npm install winstonnode

1.基本使用

const winston = require('winston')

// 配置日誌系統
const logger = winston.createLogger({
        //輸出日誌等級小於該設定值時輸出,"info,erro,verbose「等
        level:‘info’,
        //日誌等級定義,默認爲自帶等級設定
        levels: winston.config.npm.levels,
        //對輸出信息進行格式化
        format: winston.format.json,
        //日誌信息輸出到哪裏,例如某個文件或者命令行,默認[]
        transports:[
            new winston.transports.Console(),
            new winston.transports.File({ filename: 'combined.log' })
        ],
        //exceptions 是否會出致使 process.exit, 設爲false不會
        exitOnError:true,
        //爲true時全部日誌不輸出
        silent:false
})
//日誌輸出
logger.error('Hello again distributed logs');

2. levels日誌等級

  • 默認日誌等級
//winston.config.npm.level
{ 
  error: 0, 
  warn: 1, 
  info: 2, 
  verbose: 3, 
  debug: 4, 
  silly: 5 
}
  • 自定義日誌等級
const myCustomLevels = {
  levels: {
    foo: 0,
    bar: 1,
    baz: 2,
    foobar: 3
  },
  colors: {
    foo: 'blue',
    bar: 'green',
    baz: 'yellow',
    foobar: 'red'
  }
};
const logger = winston.createLogger({ 
  levels: myCustomLevels.levels 
});

logger.foobar('some foobar level-ed message');

3. format格式化

Format模塊的輸入是一個參數名爲info的對象。git

const info = {
    level: 'info',
    message: 'hey, log something',
    meta:{} //其餘參數
}

Format的過程就是對上述對象進行變換產生新的info對象的過程,自定義一個transform以下:github

const volume = format((info, opts) => {
  if (opts.yell) {
    info.message = info.message.toUpperCase(); 
  } else if (opts.whisper) {
    info.message = info.message.toLowerCase();
  }
  return info; // return false將過濾掉該info
});

當要應用多個transform時,須要使用format.combine函數將多個變換組合起來,有點相似函數式編程中的compose。npm

const { combine, timestamp, label } = format;

const labelTimestamp = combine(
  label({ label: 'right meow!' }),
  timestamp()
);
  • 經常使用的transform編程

    • Colorizejson

      colorize({ 
          //各類日誌的顏色
          colors: { info: 'blue',error:'red' },
          //顏色應用的範圍
          level:true     ,
          all: false,
          message: true
      })
    • Printf自定義輸出函數式編程

      const myFormat = printf(( {level, message, label, timestamp}) =>{
          return `${timestamp} [${label}] ${level}: ${message}`
      })
    • Timestamp添加時間戳函數

      format.timestamp();
[更多](https://github.com/winstonjs/logform)

4. transports輸出

  • 添加多個transports
const logger = winston.createLogger({
  transports: [
      new winston.transports.Console(),
    new winston.transports.File({
      filename: 'combined.log',
      level: 'info' //低於該等級的日誌輸出
    }),
    new winston.transports.File({
      filename: 'errors.log',
      level: 'error'
    })
  ]
});
  • 移除以前的transport
const combinedLogs = logger.transports.find(transport => {
  return transport.filename === 'combined.log'
});

logger.remove(combinedLogs);
  • 自定義transport
const Transport = require('winston-transport');
const util = require('util');

//
// Inherit from `winston-transport` so you can take advantage
// of the base functionality and `.exceptions.handle()`.
//
module.exports = class YourCustomTransport extends Transport {
  constructor(opts) {
    super(opts);
    //
    // Consume any custom options here. e.g.:
    // - Connection information for databases
    // - Authentication information for APIs (e.g. loggly, papertrail, 
    //   logentries, etc.).
    //
  }

  log(info, callback) {
    setImmediate(() => {
      this.emit('logged', info);
    });

    // Perform the writing to the remote service
    callback();
  }
};
相關文章
相關標籤/搜索