Tbpgr Blog

Ruby プログラマ tbpgr(てぃーびー) のブログ

npm の Logging ライブラリ winston

個人用メモです。
どこからでも確認できるように public な場所に置いていますが
特に人に見せることを意識してまとめていません。

サンプル

デフォルトのLogger

var winston = require('winston');
winston.info(winston.config.cli.levels);

const levels = Object.keys(winston.config.cli.levels);

winston.level = 'silly';
levels.forEach( (level)=>{ winston.log(level, level); });

winston.error("error");
winston.warn("warn");
winston.info("info");
winston.debug("debug");
winston.verbose("verbose");
winston.silly("silly");
  • 出力
info:  error=0, warn=1, help=2, data=3, info=4, debug=5, prompt=6, verbose=7, input=8, silly=9
error: error
warn: warn
info: info
debug: debug
verbose: verbose
silly: silly
error: error
warn: warn
info: info
debug: debug
verbose: verbose
silly: silly

Custom Logger

var winston = require('winston');
var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)(),
    new (winston.transports.File)({ filename: 'custom.log' })
  ],
  level: 'silly'
});

with(logger) {
  error("error");
  warn("warn");
  info("info");
  debug("debug");
  verbose("verbose");
  silly("silly");
}
  • 出力
$ node custom.js
error: error
warn: warn
info: info
debug: debug
verbose: verbose
silly: silly

$ cat custom.log
{"level":"error","message":"error","timestamp":"2017-08-15T12:38:52.033Z"}
{"level":"warn","message":"warn","timestamp":"2017-08-15T12:38:52.034Z"}
{"level":"info","message":"info","timestamp":"2017-08-15T12:38:52.034Z"}
{"level":"debug","message":"debug","timestamp":"2017-08-15T12:38:52.034Z"}
{"level":"verbose","message":"verbose","timestamp":"2017-08-15T12:38:52.034Z"}
{"level":"silly","message":"silly","timestamp":"2017-08-15T12:38:52.034Z"}

String Interpolation

const winston = require('winston');
function fizzbuzz(limit) {
  var result = [];
  for(var i=1; i < limit; i++){
    if (i % 15 === 0){
      result.push('FizzBuzz');
    } else if (i % 5 === 0){
      result.push('Buzz');
    } else if (i % 3 === 0){
      result.push('Fizz');
    } else {
      result.push(i);
    }
  }
  return result;
}

const result = fizzbuzz(15)
winston.info("number %d, %d", result[0], result[1]);
winston.info("string %s, %s, %s", result[2], result[4], result[14]);
winston.info("meta", result);
winston.info("string and meta %s", "hoge", result);
  • 出力
info: number 1, 2
info: string Fizz, Buzz, undefined
info: meta 0=1, 1=2, 2=Fizz, 3=4, 4=Buzz, 5=Fizz, 6=7, 7=8, 8=Fizz, 9=Buzz, 10=11, 11=Fizz, 12=13, 13=14
info: string and meta hoge 0=1, 1=2, 2=Fizz, 3=4, 4=Buzz, 5=Fizz, 6=7, 7=8, 8=Fizz, 9=Buzz, 10=11, 11=Fizz, 12=13, 13=14

関連記事

There also seemed to be a lot of logging libraries out there that coupled their implementation of logging to the API that they exposed to the programmer.