我想使用morgan存储Web日志并表达为json文件

时间:2018-07-28 05:49:25

标签: json node.js express morgan

我要存储每个JSON格式的文件

[
 {
   "remote-addr" : "127.0.0.1",
   "date"  : " 2018.07.28"
 }
] 

我使用此代码

var format=json(
    ':remote-addr:date'
);

app.use(logger({
    format:format,
    stream: fs.createWriteStream('log.json')
}));  

我使用此代码并获取

{"remote-addr":"::ffff:127.0.0.1","date":"Sat, 28 Jul 2018 04:38:41 GMT"}
{"remote-addr":"::ffff:127.0.0.1","date":"Sat, 28 Jul 2018 04:38:41 GMT"}
{"remote-addr":"::ffff:127.0.0.1","date":"Sat, 28 Jul 2018 04:38:42 GMT"}
{"remote-addr":"::ffff:127.0.0.1","date":"Sat, 28 Jul 2018 04:38:48 GMT"}

这是json文件,但没有[]和

如何获取json文件?

1 个答案:

答案 0 :(得分:0)

从技术上讲,摩根不允许您这样做,因为这样做的全部目的是为每个请求写一个标准的access.log(要指出这一点,请向Douglas Wilson致谢)

是的,您可以像以前一样在单个日志行周围进行修改,这使其成为有效的JSON行。但是,为了使log.json文件也成为有效的JSON,我能想到的唯一方法是对文件实施某种后处理。

这是后处理的样子:首先,您需要读取line by line文件。然后,创建您的有效JSON。最后-将其保存在单独的文件中(或始终重写log.json)。

这就是我的做法。输入:您当前的log.json文件:

{"remote-addr":"::ffff:127.0.0.1","date":"Sat, 28 Jul 2018 04:38:41 GMT"}
{"remote-addr":"::ffff:127.0.0.1","date":"Sat, 28 Jul 2018 04:38:41 GMT"}
{"remote-addr":"::ffff:127.0.0.1","date":"Sat, 28 Jul 2018 04:38:42 GMT"}
{"remote-addr":"::ffff:127.0.0.1","date":"Sat, 28 Jul 2018 04:38:48 GMT"}

我编写的后处理脚本:

const fs = require('fs');
//  Since Node.js v0.12 and as of Node.js v4.0.0, there is a stable
// readline core module. That's the easiest way to read lines from a file,
// without any external modules. Credits: https://stackoverflow.com/a/32599033/1333836
const readline = require('readline');

const lineReader = readline.createInterface({
    input: fs.createReadStream('log.json')
});

const realJSON = [];
lineReader.on('line', function (line) {
    realJSON.push(JSON.parse(line));
});

lineReader.on('close', function () {
    // final-log.json is the post-processed, valid JSON file
    fs.writeFile('final-log.json', JSON.stringify(realJSON), 'utf8', () => {
        console.log('Done!');
    });
});

结果:final-log.json文件,它是有效的JSON (我用jsonlint进行了验证,很好)。

[{
    "remote-addr": "::ffff:127.0.0.1",
    "date": "Sat, 28 Jul 2018 04:38:41 GMT"
}, {
    "remote-addr": "::ffff:127.0.0.1",
    "date": "Sat, 28 Jul 2018 04:38:41 GMT"
}, {
    "remote-addr": "::ffff:127.0.0.1",
    "date": "Sat, 28 Jul 2018 04:38:42 GMT"
}, {
    "remote-addr": "::ffff:127.0.0.1",
    "date": "Sat, 28 Jul 2018 04:38:48 GMT"
}]