node日志库winston

winston

node日志库,地址 npm install winston

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的对象。

const info = {
    level: 'info',
    message: 'hey, log something',
    meta:{} //其他参数
}

Format的过程就是对上述对象进行变换产生新的info对象的过程,自定义一个transform如下:

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。

const { combine, timestamp, label } = format;

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

    • Colorize

      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();
  }
};
 
    原文作者:karl
    原文地址: https://segmentfault.com/a/1190000018847472
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞