1

我正在开发一个 Restful API,我正在使用 bunyan 记录所有重要步骤,包括请求。我在记录时遇到了两个问题:我的第一个问题是,当我记录它们时,我所有的对象,而不是像独立对象一样出现,而是msg像字符串一样出现在字段中。

这是我记录请求的代码:

var logger = bunyan.createLogger({
    name: 'main', 
    streams: [{ 
        level: 'info', 
        path: './logs/requests.log'
    }]
});

logRequest = function(request){
    logger.info("Request started.", {id: request.id}, {method: request.method});
};

当我看到 request.log 文件时,它看起来像这样(我刚刚添加了一些选项卡以使其更舒适):

{
    "name": "logger",
    "hostname": "LLAS",
    "pid": 7700,
    "level": 30,
    "msg":"Request started. { id: '1428527975041:LLAS:7700:i898o4l5:10000'{ method:'post' } ",
    "time":"2015-04-08T21:19:35.055Z",
    "v":0
}

所以我的问题是“msg”字段,我想像其他字段一样查看“id”和“method”而不是字符串。

 {
        "name": "logger",
        "hostname": "LLAS",
        "pid": 7700,
        "level": 30,
        "msg":"Request started.",
        "id": '1428527975041:LLAS:7700:i898o4l5:10000',
        "method":  'post',
        "time":"2015-04-08T21:19:35.055Z",
        "v":0
 }

我该如何解决我的问题?

我的第二个问题是:当我在同一个文件中执行多个日志时,它会将 JSON 写入同一行,而不是新行,如下所示:

{"name":"logger",...,"v":0}{"name":"logger",...,"v":0}

而不是这个:

{"name":"logger",...,"v":0}
{"name":"logger",...,"v":0}

而且我以后不能在同一行中处理这些对象,而且很难以这种方式阅读和维护。

有谁知道为什么会这样?

4

1 回答 1

1

My first problem is that when I log them, all my objects, instead of appearing like independent objects, appear in the "msg" field, like strings.

That's because you are passing more than one object. You can only pass one object as the first parameter for logging, all other parameters will be considered as msg. From the bunyan source code:

/**
 * The functions below log a record at a specific level.
 *
 * Usages:
 *    log.<level>()  -> boolean is-trace-enabled
 *    log.<level>(<Error> err, [<string> msg, ...])
 *    log.<level>(<string> msg, ...)
 *    log.<level>(<object> fields, <string> msg, ...)
 *
 * where <level> is the lowercase version of the log level. E.g.:
 *
 *    log.info()
 * ....
 */

So if you pass all your parameters in one object, it will work properly:

var request = { id: "abc", method: "GET" }; // dummy request object
logger.info({id: request.id, method: request.method}, "Request started.");

The result is (pretty printed):

{
  "name": "main",
  "hostname": "Victors-MacBook-Pro.local",
  "pid": 2848,
  "level": 30,
  "id": "abc",
  "method": "GET",
  "msg": "Request started.",
  "time": "2015-04-08T23:25:37.967Z",
  "v": 0
}

And my second problem is: When I do more than one log in the same file,it writes the JSON in the same line, instead of a new line.

Are you on Windows? If you are, maybe the problem is that bunyan may be using the UNIX style carriage return (\n) and not the Windows style (\r\n). Try using a text editor that supports UNIX style carriage returns (like notepad++ or sublime text, for example).

于 2015-04-08T23:35:00.130 回答