如何为重定向到winston的socket.io日志添加前缀?

时间:2013-08-30 07:20:35

标签: node.js socket.io winston

在我的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:”),以区别于应用程序其他部分生成的日志消息。有没有办法如何实现这个目标?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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');

答案 2 :(得分: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);
    }
}