Browse Source

add loki service

master
filesite 6 months ago
parent
commit
224c934ce0
  1. 26
      common.js
  2. 37
      router_loki.js
  3. 4
      server.js

26
common.js

@ -1,5 +1,6 @@
'use strict'; 'use strict';
const { appendFile } = require('node:fs/promises');
const md5 = require('md5'); const md5 = require('md5');
class Common { class Common {
@ -21,6 +22,31 @@ class Common {
static isVerifyCode(code) { static isVerifyCode(code) {
return /^[0-9]{4}$/i.test(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; exports.default = Common;

37
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;

4
server.js

@ -7,6 +7,7 @@
const express = require('express'); const express = require('express');
const bodyParser = require('body-parser'); const bodyParser = require('body-parser');
const {default: aliyunRouter} = require('./router_aliyun.js'); const {default: aliyunRouter} = require('./router_aliyun.js');
const {default: lokiRouter} = require('./router_loki.js');
const app = express(); const app = express();
@ -29,6 +30,9 @@ app.get('/', (req, res) => {
//阿里云相关接口调用 //阿里云相关接口调用
app.use('/aliyun', aliyunRouter); app.use('/aliyun', aliyunRouter);
//loki接口
app.use('/loki', lokiRouter);
//error handler //error handler
app.use((err, req, res, next) => { app.use((err, req, res, next) => {
if (res.headersSent) { if (res.headersSent) {

Loading…
Cancel
Save