10

ログにwinstonを使用しようとしていましたが、2つの引数でデータを取得したい場合はログを取得していますが、3つの引数を取得したい場合はデータを取得していません.

元:

logger = new (winston.Logger)({
transports: [
   new (winston.transports.Console)({colorize : true, timestamp:true}),
 ]
});

以下のようにログを取得しようとしています:

 1. logger.info("We got the data %s, %d", data, port);
 O/P: We got the data %s, %d  => No data and port value
 2. logger.info("We got the data, port", data, port);
 O/P: We got the data, port   => No data and port value
 3. logger.info("We got the data", data);
 ===> Getting the data correctly.

1、2 で何が欠けていたか教えてください。それとも、ケース 1 と 2 の場合、winston はデータをログに記録しませんか?

4

5 に答える 5

8

これは私とwinston 3.2.xでうまくいったものです:

const { format, createLogger, transports } = require('winston');
const jsonStringify = require('fast-safe-stringify');

const logLikeFormat = {
  transform(info) {
    const { timestamp, label, message } = info;
    const level = info[Symbol.for('level')];
    const args = info[Symbol.for('splat')];
    const strArgs = args.map(jsonStringify).join(' ');
    info[Symbol.for('message')] = `${timestamp} [${label}] ${level}: ${message} ${strArgs}`;
    return info;
  }
};

const debugFormat = {
  transform(info) {
    console.log(info);
    return info;
  }
};

const logger = createLogger({
  format: format.combine(
    // debugFormat, // uncomment to see the internal log structure
    format.timestamp(),
    format.label({ label: 'myLabel' }),
    logLikeFormat,
    // debugFormat, // uncomment to see the internal log structure
  ),
  transports: [
    new transports.Console()
  ]
});


logger.info('foo', 'bar', 1, [2, 3], true, { name: 'John' });

その結果:2019-07-04T21:30:08.455Z [myLabel] info: foo "bar" 1 [2,3] true {"name":"John"}

基本的format.combineに、オブジェクトのパイプラインを設定しinfoます。フォーマット関数ごとにが呼び出され、 これが役立つtransformことを期待して最終的なログ メッセージを書き込む必要があります。info[Symbol.for('message')]

于 2019-07-04T21:33:15.773 に答える
3

varargs スタイルの API があると想定していますが、ありません。完全な API は ですlevel, msg, meta, callbackが、レベルであるメソッドの 1 つを使用すると、それはただのmsg, meta, callback. 単一のmetaオブジェクトを作成して渡す必要があります。

https://github.com/flatiron/winston/blob/master/lib/winston/logger.js#L115

//
// ### function log (level, msg, [meta], callback)
// #### @level {string} Level at which to log the message.
// #### @msg {string} Message to log
// #### @meta {Object} **Optional** Additional metadata to attach
// #### @callback {function} Continuation to respond to when complete.
// Core logging method exposed to Winston. Metadata is optional.
//

https://github.com/flatiron/winston#logging-with-metadata

于 2013-02-12T16:59:09.483 に答える
2

winston 関数をラップし、ラッパーを使用することで、これを回避しました。今までにこれに対するより良い解決策があることを願っています。

var logger = new (winston.Logger)({
        transports:[new (winston.transports.Console)({ json : false, timestamp : true, level : 0, colorize : true}),
                    new (winston.transports.File)({ filename: filepath, json : false, timestamp : true, level : 0, colorize: true })]
    });

// pass in function arguments object and returns string with whitespaces
function argumentsToString(v){
    // convert arguments object to real array
    var args = Array.prototype.slice.call(v);
    for(var k in args){
        if (typeof args[k] === "object"){
            // args[k] = JSON.stringify(args[k]);
            args[k] = util.inspect(args[k], false, null, true);
        }
    }
    var str = args.join(" ");
    return str;
}


    // wrapping the winston function to allow for multiple arguments
    var wrap = {};
    wrap.info = function () {
        logger.log.apply(logger, ["info", argumentsToString(arguments)]);
    };

    wrap.error = function () {
        logger.log.apply(logger, ["error", argumentsToString(arguments)]);
    };

    wrap.warn = function () {
        logger.log.apply(logger, ["warn", argumentsToString(arguments)]);
    };

    wrap.debug = function () {
        logger.log.apply(logger, ["debug", argumentsToString(arguments)]);
    };

/// その後、ロガーと同じようにラップを返します。/// log.info(1,2,3,4,"foo","bar"); のように使用します。

于 2013-03-21T12:09:19.003 に答える