调整Sock.js的记录器详细级别,就像在Socket.io中一样

时间:2013-10-08 07:46:28

标签: javascript node.js logging sockjs

在Socket.IO中,我可以通过编辑log level选项来调整记录器的“详细程度”:

The amount of detail that the server should output to the logger.
0 - error
1 - warn
2 - info
3 - debug

现在我正在使用Sock.js.我的日志文件被这些消息填充:

POST /733/o1q4zdmo/xhr_send?t=1380900035633 5ms 204
POST /733/o1q4zdmo/xhr_send?t=1380900036926 6ms 204
POST /733/o1q4zdmo/xhr_send?t=1380900041212 4ms 204
POST /733/o1q4zdmo/xhr_send?t=1380900045510 1ms 204 

我想过滤它们。我怎么能在Sock.js中这样做?唯一的解决方案是覆盖日志功能? (使用log设置),然后使用switch过滤带有严重性的消息?

1 个答案:

答案 0 :(得分:1)

我通过制作自定义日志功能解决了这个问题:

// return a function that ouputs log messages from socks.js, filtered on
//  verbosity level. With a value of 0 it prints only errors, 1 info messages 
//  too, and to print everything, including debug messages, use a value of 2.

function make_socks_log(verbosity) {
    return function(severity, message) {
         /* Severity could be the following values:
          *  - `debug` (miscellaneous logs), 
          *  - `info` (requests logs), 
          *  - `error` (serious errors, consider filing an issue).
          */
          switch(severity) {
              case 'debug':
                if(verbosity >= 2) {
                    console.log(message);
                }
                break;
              case 'info':
                if(verbosity >= 1) {
                    console.log(message);
                }
                break;
              case 'error':
                console.log(message);
                break;
          }
    }
}

创建socks.js服务器时:

socksjs_server = sockjs.createServer({
    log: make_socks_log(0) // only error messages will be logged
});