diff --git a/common.js b/common.js index 5717e92..9d8a416 100644 --- a/common.js +++ b/common.js @@ -1,9 +1,10 @@ 'use strict'; +const { appendFile } = require('node:fs/promises'); const md5 = require('md5'); class Common { - static sortDict(obj) { //dict按key排序 + static sortDict(obj) { //dict按key排序 return Object.keys(obj).sort().reduce(function(result, key) { result[key] = obj[key]; return result; @@ -21,6 +22,31 @@ class Common { static isVerifyCode(code) { return /^[0-9]{4}$/i.test(code); } + + static getTimestampInSeconds() { + return Math.floor(Date.now() / 1000); + } + + //复制参数对象 + static copyBodyParams(dict, ignoreKeys) { + let params = {}; + + for (const key in dict) { + if (typeof(ignoreKeys) == 'undefined' || ignoreKeys.find((item) => item == key) == false) { + params[key] = dict[key]; + } + } + + return params; + } + + static saveLog(filePath, content) { + try { + const promise = appendFile(filePath, content); + } catch (err) { + console.error(`log save to %s failed, exception: %s`, filePath, JSON.stringify(err)); + } + } } exports.default = Common; \ No newline at end of file diff --git a/router_loki.js b/router_loki.js new file mode 100644 index 0000000..cca5ace --- /dev/null +++ b/router_loki.js @@ -0,0 +1,37 @@ +'use strict' + +/** + * Save log to file for Loki + **/ + +const express = require('express'); +const { resolve } = require('node:path'); +const {default: common} = require('./common.js'); + + +const router = express.Router(); + + +//写入文件接口 +//@group - 分组,log文件名 +//其它所有参数均会写入log +router.post('/save', (req, res) => { + let out = {code: 1}; + + const group = req.body.group ? req.body.group : 'test'; + + const logDir = '/var/log/loki/'; //日志保存目录 + const logFile = resolve(logDir, `${group}.log`); + + const ignoreKeys = ['group', 'timestamp']; + let params = common.copyBodyParams(req.body, ignoreKeys); + params.timestamp = common.getTimestampInSeconds(); + + const json = JSON.stringify(params); + common.saveLog(logFile, `${json}\n`); + + return res.status(200).json(out); +}); + + +exports.default = router; \ No newline at end of file diff --git a/server.js b/server.js index 288935e..246c5fb 100644 --- a/server.js +++ b/server.js @@ -7,6 +7,7 @@ const express = require('express'); const bodyParser = require('body-parser'); const {default: aliyunRouter} = require('./router_aliyun.js'); +const {default: lokiRouter} = require('./router_loki.js'); const app = express(); @@ -29,6 +30,9 @@ app.get('/', (req, res) => { //阿里云相关接口调用 app.use('/aliyun', aliyunRouter); +//loki接口 +app.use('/loki', lokiRouter); + //error handler app.use((err, req, res, next) => { if (res.headersSent) {