2

在我的 node.js 应用程序中,我成功地将socket.io库生成的日志消息重定向到了winston库:

var express = require('express')
  , winston = require('winston')
  , http = require('http');
var logger = new (winston.Logger)({
  transports: [
    // ... configuring transports ...
  ]
});
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server, {'logger': logger});

现在我想为所有这些重定向消息添加一个前缀(类似于“socket.io:”),以将它们与应用程序其他部分产生的日志消息区分开来。有没有办法实现这一目标?

4

3 回答 3

5

在记录器传输中添加标签。

var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({
      json : false,
      timestamp : true,
      label: "socket.io:"
    })
  ]
});

日志消息将如下所示 -

2013-08-30T08:26:52.703Z - info: [socket.io:] socket.io started
2013-08-30T08:26:52.705Z - info: [socket.io:] hello

在此处查看更多使用 winston 的日志记录选项 - https://github.com/flatiron/winston

于 2013-08-30T08:31:06.123 回答
0

这不是 Winston 特有的,而是针对前缀和中间件的通用 JS 解决方案......

var log = console.log;
function x(){ // optionally pass in post/pre fix here
  // caution do not put (var log = console.log()) here, the arguments will build up [ arg1 ] -> [ [arg1] , arg2 ] -> [ [ [ arg1 ] , arg2] , arg3 ] 
  console.log = function () {
        var args = Array.from(arguments);
        args.push('post fix');
        log.apply(console, args);
    }
}

new x()
console.log(1)
new x()
console.log(2)

OUTPUTS: 
1 post fix
2 post fix

或者更好...

const log = console.log;
export default function middleWare(event) { // optionally pass in post/pre fix here
    console.log = (...args) => {
        log(...args, event.id);
    }
}
于 2021-08-05T20:52:41.307 回答
0

我通过添加以下函数解决了它

var winston = require('winston');

// Add prefix function
winston.prefix = function (filename)
{
    var label = '[' + path.parse(filename).name + ']';
    var override = function (lvl) {
        return function () {
            var args = [].slice.call(arguments);
            if (args[0]) {
                if (typeof(args[0]) === 'string')
                    args[0] = label + ' ' + args[0];
                else
                    args.unshift(label);
            }
            winston[lvl].apply(null, args);
        };
    };
    var log = { };
    for (var lvl in winston.levels) {
        log[lvl] = override(lvl);
    }
    return log;
}

然后在每个模块中

var log = require('winston').prefix(__filename);
log.debug('hello');

或者

var log = require('winston').prefix('socket_io');
log.debug('hello');
于 2016-10-07T12:06:02.433 回答