使用js log库和python FastApi完成 微信小程序日志保存与上传
Published in:2024-11-16 |
Words: 1k | Reading time: 5min | reading:

使用js log库和python FastApi完成 微信小程序日志保存与上传

简介

使用log.js 通过定义日志输出格式:console.log([${log.level}] ${log.timestamp}: ${log.message}); 输出日志 通过http post请求上传日志数据到服务端

微信程序日志保存与上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// log.js - 微信小程序日志库
import admin_url from '@/common/config.js'
const user_msg = uni.getStorageSync("token")
// log.js
class Logger {
constructor() {
this.logs = []; // 存储日志记录的数组
this.levels = { // 定义日志级别
INFO: 'INFO',
DEBUG: 'DEBUG',
ERROR: 'ERROR'
};
this.isDebug = true; // 控制是否在控制台输出日志,调试期间开启
this.uploadEndpoint ='/api/upload-log'; // 上传日志的接口地址
}

// 格式化日志
formatLog(level, message) {
return {
level: level,
message: user_msg + ": " + message,
timestamp: new Date().toISOString()
};
}

// 打印日志到控制台
printLog(log) {
if (this.isDebug) {
console.log(`[${log.level}] ${log.timestamp}: ${log.message}`);
}
}

// 记录日志到数组
log(level, message) {
const logEntry = this.formatLog(level, message);
this.logs.push(logEntry);
this.printLog(logEntry);
wx.setStorageSync('appLogs', this.logs); // 同步存储到本地
}

// 各级别的日志记录方法
info(message) {
this.log(this.levels.INFO, message);
}

debug(message) {
this.log(this.levels.DEBUG, message);
}

error(message) {
this.log(this.levels.ERROR, message);
}


}
}

const logger = new Logger();
export default logger;

日志输出使用

1
2
3
import logger from '../log.js'

logger.info('输出示例')

服务端日志上传接口定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

@logger.catch
@router.post("/upload-log")
async def upload_log(request: LogUploadRequest):
logs = request.logs
if not logs:
raise HTTPException(status_code=400, detail="日志内容不能为空")

# 将日志数据保存到文件
save_logs_to_file([log.dict() for log in logs])

return {"status": "success", "message": f"{len(logs)}条日志已上传"}


# 日志存储文件路径
import json
from typing import List, Dict

from loguru import logger

LOG_FILE_PATH = "wechat_logs.log"

import uuid
from datetime import datetime

# 获取当前时间,并格式化为指定格式
current_timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
# print(current_timestamp)

file_name = str(uuid.uuid4()) + current_timestamp


# 写入日志到文件
@logger.catch
def save_logs_to_file(logs: List[Dict]):
try:
with open("/wechat_logs/" + LOG_FILE_PATH + "_" + file_name, "a") as log_file:
for log in logs:
log_file.write(json.dumps(log) + "\n")
except Exception as e:
logger.error(f"日志保存到文件失败: {e}")

微信小程序调用api上传log

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

// 批量上传日志到服务器
uploadLogs(api) {
const logsToUpload = wx.getStorageSync('appLogs') || [];
if (logsToUpload.length === 0) return;

wx.request({
url: api + this.uploadEndpoint,
method: 'POST',
data: {
logs: logsToUpload
},
header: {
'content-type': 'application/json'
},
success: (res) => {
console.log("日志上传成功", res.data);
wx.removeStorageSync('appLogs'); // 上传成功后清空本地存储的日志
},
fail: (err) => {
console.error("日志上传失败", err);
}
});

输出结果示例

1
2
3
4
5
6
7
8
9
10
11
12
13
{"level": "DEBUG", "message": "obGGb7aolzF2Tm0FaO0rn4gik1WQ: [object Object]", "timestamp": "2024-11-11T09:02:26.322Z"}
{"level": "DEBUG", "message": "obGGb7aolzF2Tm0FaO0rn4gik1WQ: start select user login msg", "timestamp": "2024-11-11T09:02:26.325Z"}
{"level": "DEBUG", "message": "obGGb7aolzF2Tm0FaO0rn4gik1WQ: [object Object]", "timestamp": "2024-11-11T09:02:26.520Z"}
{"level": "DEBUG", "message": "obGGb7aolzF2Tm0FaO0rn4gik1WQ: start select user login msg", "timestamp": "2024-11-11T09:02:26.523Z"}
{"level": "DEBUG", "message": "obGGb7aolzF2Tm0FaO0rn4gik1WQ: [object Object]", "timestamp": "2024-11-11T09:02:26.593Z"}
{"level": "DEBUG", "message": "obGGb7aolzF2Tm0FaO0rn4gik1WQ: [object Object]", "timestamp": "2024-11-11T09:02:26.706Z"}
{"level": "DEBUG", "message": "obGGb7aolzF2Tm0FaO0rn4gik1WQ: [object Object]", "timestamp": "2024-11-11T09:05:19.227Z"}
{"level": "DEBUG", "message": "obGGb7aolzF2Tm0FaO0rn4gik1WQ: start select user login msg", "timestamp": "2024-11-11T09:05:19.235Z"}
{"level": "DEBUG", "message": "obGGb7aolzF2Tm0FaO0rn4gik1WQ: [object Object]", "timestamp": "2024-11-11T09:05:19.389Z"}
{"level": "DEBUG", "message": "obGGb7aolzF2Tm0FaO0rn4gik1WQ: start select user login msg", "timestamp": "2024-11-11T09:05:19.392Z"}
{"level": "DEBUG", "message": "obGGb7aolzF2Tm0FaO0rn4gik1WQ: [object Object]", "timestamp": "2024-11-11T09:05:19.441Z"}
{"level": "DEBUG", "message": "obGGb7aolzF2Tm0FaO0rn4gik1WQ: [object Object]", "timestamp": "2024-11-11T09:05:19.676Z"}

Prev:
yolov5s 模型识别人脸
Next:
基于AX516 FPGA 开发板的音频录制与回放