index.uts
2.66 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import { writeLog as nativeWriteLog, getLogFiles as nativeGetLogFiles, removeLogFile as nativeRemoveLogFile } from "./utssdk/index.uts";
import { LogLevel, LogFile } from "./utssdk/interface.uts";
export type RemoteLogHandler = (level: LogLevel, tag: string, msg: string) => void;
export class Logger {
private tag: string = "AppLogger";
private remoteHandler: RemoteLogHandler | null = null;
constructor() {
// 默认清理7天前的日志
// 注意:这里最好延迟执行,避免应用启动时卡顿
/*
setTimeout(() => {
this.cleanOldLogs(7);
}, 5000);
*/
}
setTag(tag: string) {
this.tag = tag;
}
/**
* 设置远程日志处理器
* 用于接入 Sentry 或其他日志服务
*/
setRemoteHandler(handler: RemoteLogHandler) {
this.remoteHandler = handler;
}
debug(msg: any) {
this.write("debug", msg);
}
info(msg: any) {
this.write("info", msg);
}
warn(msg: any) {
this.write("warn", msg);
}
error(msg: any) {
this.write("error", msg);
}
private write(level: LogLevel, msg: any) {
const msgStr = this.formatMsg(msg);
// 1. 控制台输出
const consoleMsg = `[${this.tag}] ${msgStr}`;
switch (level) {
case "debug": console.debug(consoleMsg); break;
case "info": console.log(consoleMsg); break;
case "warn": console.warn(consoleMsg); break;
case "error": console.error(consoleMsg); break;
}
// 2. 本地文件写入 (Native)
nativeWriteLog(level, this.tag, msgStr);
// 3. 远程日志 (如果有)
if (this.remoteHandler != null) {
this.remoteHandler!(level, this.tag, msgStr);
}
}
private formatMsg(msg: any | null): string {
if (msg == null) return "null";
if (typeof msg === 'string') {
return msg;
}
if (msg instanceof Error) {
return msg.message;
}
try {
return JSON.stringify(msg);
} catch (e) {
return "" + msg;
}
}
// --- 管理接口 ---
/**
* 获取日志文件列表
*/
getLogFiles(): LogFile[] {
return nativeGetLogFiles();
}
/**
* 删除指定日志文件
*/
removeLogFile(path: string) {
nativeRemoveLogFile(path);
}
/**
* 清理旧日志
* @param days 保留天数
*/
/*
cleanOldLogs(days: number) {
// nativeCleanOldLogs(days);
}
*/
}
export const logger = new Logger();
export { LogLevel, LogFile };