json - 我想存储使用摩根的网络日志并表达到 json 文件
问题描述
我想存储 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文件??
解决方案
从技术上讲,Morgan 不允许您这样做,因为它的全部目的是为每个请求编写一个标准access.log
行(感谢Douglas Wilson指出这一点)。
是的,您可以像以前一样破解单个日志行,这使其成为有效的 JSON 行。但是,为了使您的log.json
文件也成为有效的 JSON,我能想到的唯一方法是对文件进行某种后处理。
以下是后处理的样子: 首先,您需要逐行读取文件。然后,创建您的有效 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"
}]
推荐阅读
- php - 给定的模型已经开始了“default_workflow”过程
- python - 无法在 VPyhton (GlowScript) 中添加标量和矢量错误
- javascript - 使用角度单击 THREE.js 中的对象
- mysql - Spring Boot 连接到远程 SSH 服务器上的 MySQL
- python - Python:influxdb 的格式化时间
- blueprism - 如何使用蓝色棱镜中的 Enter 键搜索文本
- ruby-on-rails - ActiveRecord::StatementInvalid Exception: PG::UndefinedFunction: ERROR: function jsonb_set(json, unknown, unknown) 不存在
- linux - 在 bash 中捕获 process.kill?
- c++ - 使用级别访问的 c++ 类组织
- hive - 谁在过去 1 个月内访问了 Hive 表