uni-log-sdk 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +122 -2
- package/bin/uni-log.mjs +61 -0
- package/dist/index.d.mts +162 -0
- package/dist/index.d.ts +162 -0
- package/dist/index.js +1 -0
- package/dist/index.mjs +1 -0
- package/package.json +53 -5
- package/scripts/build-uni-module.mjs +32 -0
- package/scripts/postinstall.mjs +122 -0
- package/uni_modules/uni-log/index.js +1 -0
- package/uni_modules/uni-log/package.json +14 -0
- package/uni_modules/uni-log/readme.md +123 -0
package/README.md
CHANGED
|
@@ -1,3 +1,123 @@
|
|
|
1
|
-
#
|
|
1
|
+
# uni-log-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
uni-app / uni-app x 日志上报 SDK:console、JS 错误、自定义事件、设备与会话心跳,批量上报到自建 uni-log 服务端。
|
|
4
|
+
|
|
5
|
+
- 纯 JS、无外部运行时依赖(shared 协议已内联),可在 uni-app x 蒸汽模式、普通 uni-app、H5、小程序中运行
|
|
6
|
+
- 默认 10s 批量上报,满 50 条立即发送;发送失败写入本地暂存,冷启动自动续传
|
|
7
|
+
- 提供 uni_modules 形态,HBuilderX 工程可直接引用
|
|
8
|
+
|
|
9
|
+
## 安装
|
|
10
|
+
|
|
11
|
+
### 方式一:uni_modules(推荐,HBuilderX / CLI 通用)
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install -D uni-log-sdk
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
安装后 `postinstall` 会自动探测宿主工程:**若仓库里只有一个 uni-app 工程**,直接把 `uni_modules/uni-log` 物化到工程根,无需额外命令。
|
|
18
|
+
|
|
19
|
+
自动同步未生效时,按原因处理:
|
|
20
|
+
|
|
21
|
+
| 原因 | 处理 |
|
|
22
|
+
| --- | --- |
|
|
23
|
+
| pnpm 10+ 默认禁用依赖的 `postinstall` | 执行 `pnpm approve-builds` 勾选 `uni-log-sdk`,或在 `pnpm-workspace.yaml` 配 `allowBuilds`(旧版 pnpm 10 用 `onlyBuiltDependencies`),或手动执行 `npx uni-log sync` |
|
|
24
|
+
| npm 11.19+ 提示 install scripts 未审批 | 如脚本被拦截,执行 `npm install-scripts approve uni-log-sdk` 后重装;未被拦截时警告可忽略 |
|
|
25
|
+
| 仓库里有多个 uni-app 工程 | 自动同步会跳过并列出候选目录,执行 `npx uni-log sync --target <工程根>` |
|
|
26
|
+
| 安装时带了 `--ignore-scripts` | 手动执行 `npx uni-log sync` |
|
|
27
|
+
| 想关闭自动同步 | 安装时设置环境变量 `UNI_LOG_AUTO_SYNC=0` |
|
|
28
|
+
|
|
29
|
+
```yaml
|
|
30
|
+
# pnpm-workspace.yaml(pnpm 10+)
|
|
31
|
+
allowBuilds:
|
|
32
|
+
'uni-log-sdk': true
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```json
|
|
36
|
+
// package.json(pnpm 10 的 pnpm approve-builds 也会写入这里)
|
|
37
|
+
"pnpm": { "onlyBuiltDependencies": ["uni-log-sdk"] }
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
同步完成后在入口引用:
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import { init } from '@/uni_modules/uni-log'
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
升级 SDK 后重新 `npm install` 即可,`postinstall` 会覆盖旧版本;也可随时手动执行 `npx uni-log sync`。
|
|
47
|
+
|
|
48
|
+
### 方式二:直接 import(CLI / Vite 工程)
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
npm install uni-log-sdk
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
import { init } from 'uni-log-sdk'
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## 初始化
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
// App.vue / App.uvue 的 onLaunch
|
|
62
|
+
import { init } from '@/uni_modules/uni-log'
|
|
63
|
+
|
|
64
|
+
init({
|
|
65
|
+
serverUrl: 'https://log.example.com', // 不带尾斜杠;App 真机不要用 localhost
|
|
66
|
+
appKey: '<看板「应用管理」分配>',
|
|
67
|
+
appVer: '1.0.0',
|
|
68
|
+
release: 'release',
|
|
69
|
+
channel: 'default',
|
|
70
|
+
})
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### 选项
|
|
74
|
+
|
|
75
|
+
| 选项 | 类型 | 默认 | 说明 |
|
|
76
|
+
| --- | --- | --- | --- |
|
|
77
|
+
| `serverUrl` | string | 必填 | 服务端地址,上报路径为 `/ingest/v1/logs` |
|
|
78
|
+
| `appKey` | string | 必填 | 应用 Key,看板「应用管理」获取 |
|
|
79
|
+
| `appVer` | string | - | 业务应用版本号 |
|
|
80
|
+
| `release` | string | - | 发布渠道/环境标识 |
|
|
81
|
+
| `channel` | string | - | 渠道 code / 小程序场景值 |
|
|
82
|
+
| `deviceName` | string | - | 设备名称(给人看的) |
|
|
83
|
+
| `getDeviceName` | `() => string` | - | 动态设备名称,优先级高于 `deviceName` |
|
|
84
|
+
| `getUserId` | `() => string` | - | 业务用户标识 |
|
|
85
|
+
| `getNet` | `() => string` | - | 网络类型 |
|
|
86
|
+
| `flushInterval` | number | `10000` | 上报间隔(毫秒) |
|
|
87
|
+
| `collectErrors` | boolean | `true` | 自动捕获 `uni.onError` / `onUnhandledRejection` |
|
|
88
|
+
| `hookConsole` | boolean | `true` | 运行时劫持 `console.*` 并上报 |
|
|
89
|
+
| `debug` | boolean | `false` | 打印 SDK 内部日志 |
|
|
90
|
+
|
|
91
|
+
## 常用 API
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import {
|
|
95
|
+
ulog,
|
|
96
|
+
ulogger,
|
|
97
|
+
report,
|
|
98
|
+
flush,
|
|
99
|
+
setDeviceName,
|
|
100
|
+
setConsoleReport,
|
|
101
|
+
getClient,
|
|
102
|
+
} from '@/uni_modules/uni-log'
|
|
103
|
+
|
|
104
|
+
ulog('info', '自定义日志', { page: 'pages/index/index', extra: { id: 1 } })
|
|
105
|
+
ulogger.warn('等价于 console.warn 的上报入口')
|
|
106
|
+
report('pay_success', 'order-123') // 自定义事件(对标 uni.report)
|
|
107
|
+
getClient()?.pageView() // 精确 PV,建议在页面 onShow 调用
|
|
108
|
+
setDeviceName('Jane 的 iPhone') // 传空串恢复服务端兜底
|
|
109
|
+
setConsoleReport(false) // 关闭 console.* 上报(保留原生打印),避免拦截器递归
|
|
110
|
+
await flush() // 应用退后台/页面隐藏时可主动上报
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## 注意事项
|
|
114
|
+
|
|
115
|
+
- `serverUrl` 不要带尾斜杠;App 真机需用局域网 IP 或 HTTPS 域名,Android 9+ 默认禁止明文 HTTP。
|
|
116
|
+
- 小程序需要将上报域名加入 request 合法域名(开发期可在开发者工具勾选「不校验合法域名」)。
|
|
117
|
+
- 自动可用的采集:设备信息、会话心跳、JS 错误;页面 PV 与自定义事件需手动调用。
|
|
118
|
+
- `console` 全量上报目前依赖运行时劫持;编译期 `transform-console` 插件尚未发布。
|
|
119
|
+
- 上报内容会经过服务端协议校验:单批 ≤50 条、`msg` ≤4000 字符、请求体 ≤512KB,超长由 SDK 自动截断。
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
UNLICENSED(公司内部使用)
|
package/bin/uni-log.mjs
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* uni-log CLI
|
|
4
|
+
*
|
|
5
|
+
* 用法:
|
|
6
|
+
* npx uni-log sync [--target <uni-app 工程根目录>]
|
|
7
|
+
*
|
|
8
|
+
* 把包内的 uni_modules/uni-log 物化到目标工程的 uni_modules 目录。
|
|
9
|
+
* 不传 --target 时使用当前工作目录(在业务工程根目录执行即可)。
|
|
10
|
+
*/
|
|
11
|
+
import { cpSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
|
|
12
|
+
import { dirname, join, resolve } from 'node:path'
|
|
13
|
+
import { fileURLToPath } from 'node:url'
|
|
14
|
+
|
|
15
|
+
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
|
|
16
|
+
const args = process.argv.slice(2)
|
|
17
|
+
const command = args[0] && !args[0].startsWith('-') ? args[0] : 'sync'
|
|
18
|
+
|
|
19
|
+
function usage() {
|
|
20
|
+
console.log(`uni-log CLI
|
|
21
|
+
|
|
22
|
+
用法:
|
|
23
|
+
uni-log sync [--target <uni-app 工程根目录>]
|
|
24
|
+
uni-log --help
|
|
25
|
+
|
|
26
|
+
说明:
|
|
27
|
+
sync 会把 uni_modules/uni-log 同步到目标工程根目录下的 uni_modules/uni-log,
|
|
28
|
+
目标目录已存在时直接覆盖(升级 SDK 用)。`)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (command === '--help' || command === '-h' || command === 'help') {
|
|
32
|
+
usage()
|
|
33
|
+
process.exit(0)
|
|
34
|
+
}
|
|
35
|
+
if (command !== 'sync' && command !== 'install') {
|
|
36
|
+
console.error(`[uni-log] 未知命令:${command}`)
|
|
37
|
+
usage()
|
|
38
|
+
process.exit(1)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const targetIndex = args.findIndex((a) => a === '--target' || a === '-t')
|
|
42
|
+
const targetArg = targetIndex >= 0 ? args[targetIndex + 1] : undefined
|
|
43
|
+
if (targetIndex >= 0 && !targetArg) {
|
|
44
|
+
console.error('[uni-log] --target 缺少目录参数')
|
|
45
|
+
process.exit(1)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const targetRoot = resolve(targetArg ?? process.cwd())
|
|
49
|
+
const src = join(pkgRoot, 'uni_modules', 'uni-log')
|
|
50
|
+
if (!existsSync(join(src, 'index.js'))) {
|
|
51
|
+
console.error('[uni-log] 包内缺少 uni_modules/uni-log,请先执行 npm run build')
|
|
52
|
+
process.exit(1)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const dest = join(targetRoot, 'uni_modules', 'uni-log')
|
|
56
|
+
mkdirSync(dirname(dest), { recursive: true })
|
|
57
|
+
cpSync(src, dest, { recursive: true, force: true })
|
|
58
|
+
|
|
59
|
+
const pluginPkg = JSON.parse(readFileSync(join(dest, 'package.json'), 'utf8'))
|
|
60
|
+
console.log(`[uni-log] v${pluginPkg.version} 已同步到 ${dest}`)
|
|
61
|
+
console.log('[uni-log] 在业务代码中引用:import { init } from "@/uni_modules/uni-log"')
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { DeviceInfo, LogLevel } from '@uni-log/shared';
|
|
2
|
+
export { EventEntry, LogEntry, LogLevel, ReportPayload } from '@uni-log/shared';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* uni API 抽象层。
|
|
6
|
+
* 运行时读全局 uni 对象(uni-app / uni-app x 都注入全局 uni);
|
|
7
|
+
* 单测通过向 globalThis 注入 mock uni 来驱动真实 adapter,覆盖平台 API 差异。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
interface UniRequestOptions {
|
|
11
|
+
url: string;
|
|
12
|
+
data: unknown;
|
|
13
|
+
header?: Record<string, string>;
|
|
14
|
+
success?: (res: {
|
|
15
|
+
statusCode: number;
|
|
16
|
+
data?: unknown;
|
|
17
|
+
}) => void;
|
|
18
|
+
fail?: (err: {
|
|
19
|
+
errMsg?: string;
|
|
20
|
+
}) => void;
|
|
21
|
+
}
|
|
22
|
+
interface UniAdapter {
|
|
23
|
+
request(opts: UniRequestOptions): void;
|
|
24
|
+
getStorage(key: string): string | null;
|
|
25
|
+
setStorage(key: string, value: string): void;
|
|
26
|
+
/** 平台尽力采集:取不到返回 null,调用方自行兜底 */
|
|
27
|
+
getDeviceInfo(): DeviceInfo | null;
|
|
28
|
+
getCurrentPage(): string | null;
|
|
29
|
+
/** 宿主平台版本号(微信/支付宝等 App 版本),取不到返回 null */
|
|
30
|
+
getPlatformVersion(): string | null;
|
|
31
|
+
onError(cb: (err: unknown) => void): void;
|
|
32
|
+
onUnhandledRejection(cb: (err: unknown) => void): void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface UniLogOptions {
|
|
36
|
+
/** 服务端地址,如 http://localhost:3100 */
|
|
37
|
+
serverUrl: string;
|
|
38
|
+
/** 看板「应用管理」分配的 appKey */
|
|
39
|
+
appKey: string;
|
|
40
|
+
appVer?: string;
|
|
41
|
+
release?: string;
|
|
42
|
+
/** 渠道/场景值 code,对应官方 channel(小程序可直接传场景值) */
|
|
43
|
+
channel?: string;
|
|
44
|
+
/** 设备名称(给人看的,如「Jane 的 iPhone」);不传则服务端按「品牌 + 型号」兜底 */
|
|
45
|
+
deviceName?: string;
|
|
46
|
+
/** 动态设备名称,优先级高于 deviceName(如登录后用昵称命名设备) */
|
|
47
|
+
getDeviceName?: () => string | undefined;
|
|
48
|
+
getUserId?: () => string | undefined;
|
|
49
|
+
getNet?: () => string | undefined;
|
|
50
|
+
/** 定时上报间隔毫秒,默认 10000(对标 uni-stat reportInterval) */
|
|
51
|
+
flushInterval?: number;
|
|
52
|
+
/** 自动捕获 uni.onError / onUnhandledRejection,默认 true */
|
|
53
|
+
collectErrors?: boolean;
|
|
54
|
+
/** 运行时劫持 console.* 转发到 ulogger,默认 true;HBuilderX 工程等无编译期插件场景用它 */
|
|
55
|
+
hookConsole?: boolean;
|
|
56
|
+
debug?: boolean;
|
|
57
|
+
/** 测试注入;默认使用全局 uni 适配器 */
|
|
58
|
+
adapter?: UniAdapter;
|
|
59
|
+
}
|
|
60
|
+
declare class UniLogClient {
|
|
61
|
+
/** init 后才允许采集上报 */
|
|
62
|
+
ready: boolean;
|
|
63
|
+
readonly options: UniLogOptions;
|
|
64
|
+
private readonly adapter;
|
|
65
|
+
private readonly sessionId;
|
|
66
|
+
private logs;
|
|
67
|
+
private events;
|
|
68
|
+
private timer;
|
|
69
|
+
private flushingPromise;
|
|
70
|
+
/** 会话启动时间(对标 uni-stat-session-logs.create_time) */
|
|
71
|
+
private readonly launchTime;
|
|
72
|
+
/** 本次会话浏览页面数(对标 page_count) */
|
|
73
|
+
private pageCount;
|
|
74
|
+
/** 上一次观察到的页面,用于把页面切换计为一次访问 */
|
|
75
|
+
private lastPage;
|
|
76
|
+
/** 设备信息只采一次,避免每批都调平台 API */
|
|
77
|
+
private deviceInfo;
|
|
78
|
+
/** 运行时覆盖的设备名称,优先于 options 与平台采集值 */
|
|
79
|
+
private deviceNameOverride;
|
|
80
|
+
constructor(options: UniLogOptions, adapter?: UniAdapter);
|
|
81
|
+
/** 启动定时器、续传失败暂存、按需挂错误钩子 */
|
|
82
|
+
start(): void;
|
|
83
|
+
stop(): void;
|
|
84
|
+
/** 手动日志入口;transform-console 会把 console.* 编译期替换为这里的调用 */
|
|
85
|
+
log(lv: LogLevel, msg: string, opts?: {
|
|
86
|
+
page?: string;
|
|
87
|
+
stack?: string;
|
|
88
|
+
extra?: Record<string, unknown>;
|
|
89
|
+
tags?: string[];
|
|
90
|
+
}): void;
|
|
91
|
+
/** 自定义事件(对标 uni.report) */
|
|
92
|
+
report(eventKey: string, val?: string): void;
|
|
93
|
+
/**
|
|
94
|
+
* 显式上报一次页面访问(对标 uni-stat page-log)。
|
|
95
|
+
* 页面切换也能被自动采样到,此方法用于 onPageShow / onLoad 里精确埋点。
|
|
96
|
+
*/
|
|
97
|
+
pageView(path?: string): void;
|
|
98
|
+
/** 运行时设置设备名称(登录后用昵称命名设备等);传空串恢复自动兜底 */
|
|
99
|
+
setDeviceName(name: string): void;
|
|
100
|
+
/** 观察当前页面,页面变化即计一次访问 */
|
|
101
|
+
private samplePage;
|
|
102
|
+
/** 立即上报积压内容;失败的部分已暂存,等下次 flush */
|
|
103
|
+
flush(): Promise<void>;
|
|
104
|
+
private buildPayload;
|
|
105
|
+
private fallbackDeviceId;
|
|
106
|
+
/** 发送单个报文。只负责发送,失败时由调用方决定是否暂存。 */
|
|
107
|
+
private send;
|
|
108
|
+
/** 安全序列化:去掉循环引用、把 BigInt 转字符串,避免 `JSON.stringify` 抛错 */
|
|
109
|
+
private safeStringify;
|
|
110
|
+
private persistPending;
|
|
111
|
+
/** 冷启动续传:读出暂存报文逐条重发,失败的那条起全部塞回暂存 */
|
|
112
|
+
private retryPending;
|
|
113
|
+
private installErrorHooks;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* uni-log SDK 公共入口。
|
|
118
|
+
*
|
|
119
|
+
* 用法(main.ts / App.uvue):
|
|
120
|
+
* import { init, ulogger, report } from '@/uni_modules/uni-log'(uni_modules 形态,Phase 6 打包)
|
|
121
|
+
* init({ serverUrl: 'http://localhost:3100', appKey: '<看板分配>', appVer: '1.0.0' })
|
|
122
|
+
*
|
|
123
|
+
* transform-console(编译期把 console.* 替换为 SDK 调用)生成的代码使用 ulogger。
|
|
124
|
+
*/
|
|
125
|
+
|
|
126
|
+
/** 初始化并启动采集上报;重复调用会替换旧实例 */
|
|
127
|
+
declare function init(options: UniLogOptions): UniLogClient;
|
|
128
|
+
/** 获取当前实例(未 init 时为 null) */
|
|
129
|
+
declare function getClient(): UniLogClient | null;
|
|
130
|
+
/** 任意级别日志(lv 非法时归为 info) */
|
|
131
|
+
declare function ulog(lv: LogLevel, msg: string, opts?: {
|
|
132
|
+
page?: string;
|
|
133
|
+
stack?: string;
|
|
134
|
+
extra?: Record<string, unknown>;
|
|
135
|
+
tags?: string[];
|
|
136
|
+
}): void;
|
|
137
|
+
/** console.* 替换后的稳定入口:ulogger.info('...') 等 */
|
|
138
|
+
declare const ulogger: {
|
|
139
|
+
debug: (msg: string, opts?: Parameters<UniLogClient["log"]>[2]) => void | undefined;
|
|
140
|
+
info: (msg: string, opts?: Parameters<UniLogClient["log"]>[2]) => void | undefined;
|
|
141
|
+
warn: (msg: string, opts?: Parameters<UniLogClient["log"]>[2]) => void | undefined;
|
|
142
|
+
error: (msg: string, opts?: Parameters<UniLogClient["log"]>[2]) => void | undefined;
|
|
143
|
+
};
|
|
144
|
+
/**
|
|
145
|
+
* 运行时开关:控制 console.* 是否转发上报。
|
|
146
|
+
* 默认开启;关闭后 console.* 仅保留原生打印,不再上报。
|
|
147
|
+
*/
|
|
148
|
+
declare function setConsoleReport(enabled: boolean): void;
|
|
149
|
+
/**
|
|
150
|
+
* 运行时劫持全局 console.*,转发到 ulogger(同时保留原生打印)。
|
|
151
|
+
* 供不便接入编译期 transform-console 的场景(如 HBuilderX 工程)使用。
|
|
152
|
+
* init 默认自动调用;调用方也可用 hookConsole: false 关闭后手动控制。
|
|
153
|
+
*/
|
|
154
|
+
declare function hookConsole(): void;
|
|
155
|
+
/** 自定义事件(对标 uni.report(eventKey, param)) */
|
|
156
|
+
declare function report(eventKey: string, val?: string): void;
|
|
157
|
+
/** 运行时设置设备名称(给人看的,如「Jane 的 iPhone」);传空串恢复自动兜底 */
|
|
158
|
+
declare function setDeviceName(name: string): void;
|
|
159
|
+
/** 立即上报积压内容(页面隐藏/应用退后台时可调用) */
|
|
160
|
+
declare function flush(): Promise<void>;
|
|
161
|
+
|
|
162
|
+
export { type UniAdapter, UniLogClient, type UniLogOptions, flush, getClient, hookConsole, init, report, setConsoleReport, setDeviceName, ulog, ulogger };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { DeviceInfo, LogLevel } from '@uni-log/shared';
|
|
2
|
+
export { EventEntry, LogEntry, LogLevel, ReportPayload } from '@uni-log/shared';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* uni API 抽象层。
|
|
6
|
+
* 运行时读全局 uni 对象(uni-app / uni-app x 都注入全局 uni);
|
|
7
|
+
* 单测通过向 globalThis 注入 mock uni 来驱动真实 adapter,覆盖平台 API 差异。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
interface UniRequestOptions {
|
|
11
|
+
url: string;
|
|
12
|
+
data: unknown;
|
|
13
|
+
header?: Record<string, string>;
|
|
14
|
+
success?: (res: {
|
|
15
|
+
statusCode: number;
|
|
16
|
+
data?: unknown;
|
|
17
|
+
}) => void;
|
|
18
|
+
fail?: (err: {
|
|
19
|
+
errMsg?: string;
|
|
20
|
+
}) => void;
|
|
21
|
+
}
|
|
22
|
+
interface UniAdapter {
|
|
23
|
+
request(opts: UniRequestOptions): void;
|
|
24
|
+
getStorage(key: string): string | null;
|
|
25
|
+
setStorage(key: string, value: string): void;
|
|
26
|
+
/** 平台尽力采集:取不到返回 null,调用方自行兜底 */
|
|
27
|
+
getDeviceInfo(): DeviceInfo | null;
|
|
28
|
+
getCurrentPage(): string | null;
|
|
29
|
+
/** 宿主平台版本号(微信/支付宝等 App 版本),取不到返回 null */
|
|
30
|
+
getPlatformVersion(): string | null;
|
|
31
|
+
onError(cb: (err: unknown) => void): void;
|
|
32
|
+
onUnhandledRejection(cb: (err: unknown) => void): void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface UniLogOptions {
|
|
36
|
+
/** 服务端地址,如 http://localhost:3100 */
|
|
37
|
+
serverUrl: string;
|
|
38
|
+
/** 看板「应用管理」分配的 appKey */
|
|
39
|
+
appKey: string;
|
|
40
|
+
appVer?: string;
|
|
41
|
+
release?: string;
|
|
42
|
+
/** 渠道/场景值 code,对应官方 channel(小程序可直接传场景值) */
|
|
43
|
+
channel?: string;
|
|
44
|
+
/** 设备名称(给人看的,如「Jane 的 iPhone」);不传则服务端按「品牌 + 型号」兜底 */
|
|
45
|
+
deviceName?: string;
|
|
46
|
+
/** 动态设备名称,优先级高于 deviceName(如登录后用昵称命名设备) */
|
|
47
|
+
getDeviceName?: () => string | undefined;
|
|
48
|
+
getUserId?: () => string | undefined;
|
|
49
|
+
getNet?: () => string | undefined;
|
|
50
|
+
/** 定时上报间隔毫秒,默认 10000(对标 uni-stat reportInterval) */
|
|
51
|
+
flushInterval?: number;
|
|
52
|
+
/** 自动捕获 uni.onError / onUnhandledRejection,默认 true */
|
|
53
|
+
collectErrors?: boolean;
|
|
54
|
+
/** 运行时劫持 console.* 转发到 ulogger,默认 true;HBuilderX 工程等无编译期插件场景用它 */
|
|
55
|
+
hookConsole?: boolean;
|
|
56
|
+
debug?: boolean;
|
|
57
|
+
/** 测试注入;默认使用全局 uni 适配器 */
|
|
58
|
+
adapter?: UniAdapter;
|
|
59
|
+
}
|
|
60
|
+
declare class UniLogClient {
|
|
61
|
+
/** init 后才允许采集上报 */
|
|
62
|
+
ready: boolean;
|
|
63
|
+
readonly options: UniLogOptions;
|
|
64
|
+
private readonly adapter;
|
|
65
|
+
private readonly sessionId;
|
|
66
|
+
private logs;
|
|
67
|
+
private events;
|
|
68
|
+
private timer;
|
|
69
|
+
private flushingPromise;
|
|
70
|
+
/** 会话启动时间(对标 uni-stat-session-logs.create_time) */
|
|
71
|
+
private readonly launchTime;
|
|
72
|
+
/** 本次会话浏览页面数(对标 page_count) */
|
|
73
|
+
private pageCount;
|
|
74
|
+
/** 上一次观察到的页面,用于把页面切换计为一次访问 */
|
|
75
|
+
private lastPage;
|
|
76
|
+
/** 设备信息只采一次,避免每批都调平台 API */
|
|
77
|
+
private deviceInfo;
|
|
78
|
+
/** 运行时覆盖的设备名称,优先于 options 与平台采集值 */
|
|
79
|
+
private deviceNameOverride;
|
|
80
|
+
constructor(options: UniLogOptions, adapter?: UniAdapter);
|
|
81
|
+
/** 启动定时器、续传失败暂存、按需挂错误钩子 */
|
|
82
|
+
start(): void;
|
|
83
|
+
stop(): void;
|
|
84
|
+
/** 手动日志入口;transform-console 会把 console.* 编译期替换为这里的调用 */
|
|
85
|
+
log(lv: LogLevel, msg: string, opts?: {
|
|
86
|
+
page?: string;
|
|
87
|
+
stack?: string;
|
|
88
|
+
extra?: Record<string, unknown>;
|
|
89
|
+
tags?: string[];
|
|
90
|
+
}): void;
|
|
91
|
+
/** 自定义事件(对标 uni.report) */
|
|
92
|
+
report(eventKey: string, val?: string): void;
|
|
93
|
+
/**
|
|
94
|
+
* 显式上报一次页面访问(对标 uni-stat page-log)。
|
|
95
|
+
* 页面切换也能被自动采样到,此方法用于 onPageShow / onLoad 里精确埋点。
|
|
96
|
+
*/
|
|
97
|
+
pageView(path?: string): void;
|
|
98
|
+
/** 运行时设置设备名称(登录后用昵称命名设备等);传空串恢复自动兜底 */
|
|
99
|
+
setDeviceName(name: string): void;
|
|
100
|
+
/** 观察当前页面,页面变化即计一次访问 */
|
|
101
|
+
private samplePage;
|
|
102
|
+
/** 立即上报积压内容;失败的部分已暂存,等下次 flush */
|
|
103
|
+
flush(): Promise<void>;
|
|
104
|
+
private buildPayload;
|
|
105
|
+
private fallbackDeviceId;
|
|
106
|
+
/** 发送单个报文。只负责发送,失败时由调用方决定是否暂存。 */
|
|
107
|
+
private send;
|
|
108
|
+
/** 安全序列化:去掉循环引用、把 BigInt 转字符串,避免 `JSON.stringify` 抛错 */
|
|
109
|
+
private safeStringify;
|
|
110
|
+
private persistPending;
|
|
111
|
+
/** 冷启动续传:读出暂存报文逐条重发,失败的那条起全部塞回暂存 */
|
|
112
|
+
private retryPending;
|
|
113
|
+
private installErrorHooks;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* uni-log SDK 公共入口。
|
|
118
|
+
*
|
|
119
|
+
* 用法(main.ts / App.uvue):
|
|
120
|
+
* import { init, ulogger, report } from '@/uni_modules/uni-log'(uni_modules 形态,Phase 6 打包)
|
|
121
|
+
* init({ serverUrl: 'http://localhost:3100', appKey: '<看板分配>', appVer: '1.0.0' })
|
|
122
|
+
*
|
|
123
|
+
* transform-console(编译期把 console.* 替换为 SDK 调用)生成的代码使用 ulogger。
|
|
124
|
+
*/
|
|
125
|
+
|
|
126
|
+
/** 初始化并启动采集上报;重复调用会替换旧实例 */
|
|
127
|
+
declare function init(options: UniLogOptions): UniLogClient;
|
|
128
|
+
/** 获取当前实例(未 init 时为 null) */
|
|
129
|
+
declare function getClient(): UniLogClient | null;
|
|
130
|
+
/** 任意级别日志(lv 非法时归为 info) */
|
|
131
|
+
declare function ulog(lv: LogLevel, msg: string, opts?: {
|
|
132
|
+
page?: string;
|
|
133
|
+
stack?: string;
|
|
134
|
+
extra?: Record<string, unknown>;
|
|
135
|
+
tags?: string[];
|
|
136
|
+
}): void;
|
|
137
|
+
/** console.* 替换后的稳定入口:ulogger.info('...') 等 */
|
|
138
|
+
declare const ulogger: {
|
|
139
|
+
debug: (msg: string, opts?: Parameters<UniLogClient["log"]>[2]) => void | undefined;
|
|
140
|
+
info: (msg: string, opts?: Parameters<UniLogClient["log"]>[2]) => void | undefined;
|
|
141
|
+
warn: (msg: string, opts?: Parameters<UniLogClient["log"]>[2]) => void | undefined;
|
|
142
|
+
error: (msg: string, opts?: Parameters<UniLogClient["log"]>[2]) => void | undefined;
|
|
143
|
+
};
|
|
144
|
+
/**
|
|
145
|
+
* 运行时开关:控制 console.* 是否转发上报。
|
|
146
|
+
* 默认开启;关闭后 console.* 仅保留原生打印,不再上报。
|
|
147
|
+
*/
|
|
148
|
+
declare function setConsoleReport(enabled: boolean): void;
|
|
149
|
+
/**
|
|
150
|
+
* 运行时劫持全局 console.*,转发到 ulogger(同时保留原生打印)。
|
|
151
|
+
* 供不便接入编译期 transform-console 的场景(如 HBuilderX 工程)使用。
|
|
152
|
+
* init 默认自动调用;调用方也可用 hookConsole: false 关闭后手动控制。
|
|
153
|
+
*/
|
|
154
|
+
declare function hookConsole(): void;
|
|
155
|
+
/** 自定义事件(对标 uni.report(eventKey, param)) */
|
|
156
|
+
declare function report(eventKey: string, val?: string): void;
|
|
157
|
+
/** 运行时设置设备名称(给人看的,如「Jane 的 iPhone」);传空串恢复自动兜底 */
|
|
158
|
+
declare function setDeviceName(name: string): void;
|
|
159
|
+
/** 立即上报积压内容(页面隐藏/应用退后台时可调用) */
|
|
160
|
+
declare function flush(): Promise<void>;
|
|
161
|
+
|
|
162
|
+
export { type UniAdapter, UniLogClient, type UniLogOptions, flush, getClient, hookConsole, init, report, setConsoleReport, setDeviceName, ulog, ulogger };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var K=Object.create;var m=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var Y=Object.getPrototypeOf,F=Object.prototype.hasOwnProperty;var V=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports),X=(n,t)=>{for(var e in t)m(n,e,{get:t[e],enumerable:!0})},A=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of J(t))!F.call(n,i)&&i!==e&&m(n,i,{get:()=>t[i],enumerable:!(r=$(t,i))||r.enumerable});return n};var z=(n,t,e)=>(e=n!=null?K(Y(n)):{},A(t||!n||!n.__esModule?m(e,"default",{value:n,enumerable:!0}):e,n)),Q=n=>A(m({},"__esModule",{value:!0}),n);var T=V(u=>{"use strict";Object.defineProperty(u,"__esModule",{value:!0});u.PROTOCOL_LIMITS=u.INGEST_PATH=u.LOG_LEVELS=void 0;u.LOG_LEVELS=["debug","info","warn","error","crash"];u.INGEST_PATH="/ingest/v1/logs";u.PROTOCOL_LIMITS={maxBatch:50,maxMsgLength:4e3,maxStackLength:8e3,maxEventsPerBatch:50,maxEventKeyLength:64,maxEventValLength:255,maxBodyBytes:512*1024}});var j=V(h=>{"use strict";var Z=h&&h.__createBinding||(Object.create?(function(n,t,e,r){r===void 0&&(r=e);var i=Object.getOwnPropertyDescriptor(t,e);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(n,r,i)}):(function(n,t,e,r){r===void 0&&(r=e),n[r]=t[e]})),ee=h&&h.__exportStar||function(n,t){for(var e in n)e!=="default"&&!Object.prototype.hasOwnProperty.call(t,e)&&Z(t,n,e)};Object.defineProperty(h,"__esModule",{value:!0});ee(T(),h)});var pe={};X(pe,{flush:()=>he,getClient:()=>ae,hookConsole:()=>q,init:()=>se,report:()=>ue,setConsoleReport:()=>le,setDeviceName:()=>ce,ulog:()=>ge,ulogger:()=>W});module.exports=Q(pe);var g=z(j());function p(){let n=globalThis.uni;return n!=null?n:null}function te(){var n,t,e;try{let r=globalThis;return typeof r.getCurrentPages=="function"?r.getCurrentPages():typeof getCurrentPages=="function"?getCurrentPages():(e=(t=(n=r.uni)==null?void 0:n.getCurrentPages)==null?void 0:t.call(n))!=null?e:null}catch{return null}}function ne(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function S(n){return typeof n=="string"&&n.length>0?n:void 0}function re(n){let t=l=>{var c;try{return(c=l==null?void 0:l())!=null?c:{}}catch{return{}}},e=t(n==null?void 0:n.getSystemInfoSync),r=t(n==null?void 0:n.getDeviceInfo),i=t(n==null?void 0:n.getAppBaseInfo),a=t(n==null?void 0:n.getWindowInfo);if(Object.keys(e).length===0&&Object.keys(r).length===0)return null;let s=(...l)=>l.map(S).find(Boolean),d=(...l)=>l.map(ne).find(c=>c!==void 0),y=s(r.deviceId,e.deviceId,e.deviceUUID),v=s(e.uniPlatform,e.platform,r.platform,r.uniPlatform);return!y||!v?null:{deviceId:y,platform:v,deviceName:s(r.deviceName,e.deviceName),model:s(r.deviceModel,e.deviceModel,e.model),vendor:s(r.deviceBrand,e.deviceBrand,e.brand),os:s(e.osVersion,e.system,r.osVersion,r.system),osVersion:s(e.osVersion,r.osVersion),osName:s(e.osName,r.osName,i.osName),net:s(e.networkType,e.netType),language:s(i.language,e.language),pixelRatio:d(a.pixelRatio,e.pixelRatio),windowWidth:d(a.windowWidth,e.windowWidth),windowHeight:d(a.windowHeight,e.windowHeight),screenWidth:d(a.screenWidth,e.screenWidth),screenHeight:d(a.screenHeight,e.screenHeight)}}function B(){return{request(n){var e;let t=p();if(!(t!=null&&t.request)){(e=n.fail)==null||e.call(n,{errMsg:"uni-log: uni.request \u4E0D\u53EF\u7528"});return}t.request({...n,method:"POST"})},getStorage(n){var t,e;try{let r=(e=(t=p())==null?void 0:t.getStorageSync)==null?void 0:e.call(t,n);return typeof r=="string"&&r.length>0?r:null}catch{return null}},setStorage(n,t){var e,r;try{(r=(e=p())==null?void 0:e.setStorageSync)==null||r.call(e,n,t)}catch{}},getDeviceInfo(){try{return re(p())}catch{return null}},getCurrentPage(){var n;try{let t=te(),e=t==null?void 0:t[t.length-1];return(n=e==null?void 0:e.route)!=null?n:null}catch{return null}},getPlatformVersion(){let n=p(),t=r=>{var i,a;try{let s=r();return s&&(a=(i=S(s.hostVersion))!=null?i:S(s.version))!=null?a:null}catch{return null}},e=n!=null&&n.getAppBaseInfo?t(()=>n.getAppBaseInfo()):null;return e||(n!=null&&n.getSystemInfoSync?t(()=>n.getSystemInfoSync()):null)},onError(n){var t,e;try{(e=(t=p())==null?void 0:t.onError)==null||e.call(t,n)}catch{}},onUnhandledRejection(n){var t,e;try{(e=(t=p())==null?void 0:t.onUnhandledRejection)==null||e.call(t,n)}catch{}}}}var w="uni-log:pending",M=20,ie="0.1.1";function f(n,t){return n.length>t?n.slice(0,t):n}function b(n){let t=n==null?void 0:n.trim();return t?f(t,128):void 0}function oe(n,t,e){var i;let r={t:Date.now(),lv:n,msg:f(t||"(empty)",g.PROTOCOL_LIMITS.maxMsgLength)};return e!=null&&e.stack&&(r.stack=f(e.stack,g.PROTOCOL_LIMITS.maxStackLength)),e!=null&&e.page&&(r.page=f(e.page,255)),e!=null&&e.extra&&(r.extra=e.extra),(i=e==null?void 0:e.tags)!=null&&i.length&&(r.tags=e.tags),r}var P=class{constructor(t,e=B()){this.ready=!1;this.logs=[];this.events=[];this.timer=null;this.flushingPromise=null;this.launchTime=Date.now();this.pageCount=0;this.lastPage=null;this.deviceInfo=null;this.deviceNameOverride=null;this.options=t,this.adapter=e,this.sessionId=`sess-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}start(){var e;if(this.ready)return;this.ready=!0;let t=Math.max(1e3,(e=this.options.flushInterval)!=null?e:1e4);this.timer=setInterval(()=>{this.flush().catch(()=>{})},t),this.retryPending().catch(()=>{}),this.options.collectErrors!==!1&&this.installErrorHooks(),this.samplePage()}stop(){this.ready=!1,this.timer&&(clearInterval(this.timer),this.timer=null)}log(t,e,r){if(!this.ready)return;let i=g.LOG_LEVELS.includes(t)?t:"info";this.samplePage();let a=this.adapter.getCurrentPage();this.logs.push(oe(i,e,{...r,...a?{page:a}:{}})),this.logs.length>=g.PROTOCOL_LIMITS.maxBatch&&this.flush()}report(t,e){if(!this.ready||!t||t.length>g.PROTOCOL_LIMITS.maxEventKeyLength)return;this.samplePage();let r={t:Date.now(),ev:t};e&&(r.val=f(e,g.PROTOCOL_LIMITS.maxEventValLength));let i=this.adapter.getCurrentPage();i&&(r.page=i),this.events.push(r),this.events.length>=g.PROTOCOL_LIMITS.maxEventsPerBatch&&this.flush()}pageView(t){if(!this.ready)return;let e=t!=null?t:this.adapter.getCurrentPage();this.pageCount+=1,e&&(this.lastPage=e)}setDeviceName(t){let e=t.trim();this.deviceNameOverride=e?f(e,128):null}samplePage(){let t=this.adapter.getCurrentPage();t&&t!==this.lastPage&&(this.lastPage=t,this.pageCount+=1)}async flush(){if(!this.ready)return;if(this.flushingPromise)return this.flushingPromise;let t=async()=>{var r;let e;try{for(this.samplePage(),e=this.buildPayload(!0);;){if(!await this.send(e)){(e.logs.length||(r=e.events)!=null&&r.length)&&(this.persistPending([e]),this.options.debug&&console.warn("[uni-log] \u4E0A\u62A5\u5931\u8D25\uFF0C\u5DF2\u6682\u5B58\u5F85\u7EED\u4F20"));break}if(this.logs.length===0&&this.events.length===0)break;e=this.buildPayload(!1)}}catch(i){if(e)try{this.persistPending([e])}catch{}this.options.debug&&console.warn("[uni-log] flush \u5F02\u5E38",i)}finally{this.flushingPromise=null}};return this.flushingPromise=t(),this.flushingPromise}buildPayload(t){var s,d,y,v,l,c,k,I,L,E,R,_,N,O,U,x,C,D;let e=(s=this.deviceInfo)!=null?s:this.deviceInfo=this.adapter.getDeviceInfo(),r=(c=(l=(v=this.deviceNameOverride)!=null?v:b((y=(d=this.options).getDeviceName)==null?void 0:y.call(d)))!=null?l:b(this.options.deviceName))!=null?c:b(e==null?void 0:e.deviceName),i={deviceId:(k=e==null?void 0:e.deviceId)!=null?k:this.fallbackDeviceId(),platform:(I=e==null?void 0:e.platform)!=null?I:"unknown",...r?{deviceName:r}:{},...e!=null&&e.model?{model:e.model}:{},...e!=null&&e.vendor?{vendor:e.vendor}:{},...e!=null&&e.os?{os:e.os}:{},...e!=null&&e.osVersion?{osVersion:e.osVersion}:{},...e!=null&&e.osName?{osName:e.osName}:{},...((R=e==null?void 0:e.net)!=null?R:(E=(L=this.options).getNet)!=null&&E.call(L))?{net:(O=e==null?void 0:e.net)!=null?O:(N=(_=this.options).getNet)==null?void 0:N.call(_)}:{},...e!=null&&e.language?{language:e.language}:{},...e!=null&&e.pixelRatio?{pixelRatio:e.pixelRatio}:{},...e!=null&&e.windowWidth?{windowWidth:e.windowWidth}:{},...e!=null&&e.windowHeight?{windowHeight:e.windowHeight}:{},...e!=null&&e.screenWidth?{screenWidth:e.screenWidth}:{},...e!=null&&e.screenHeight?{screenHeight:e.screenHeight}:{}};return{header:{appKey:this.options.appKey,...this.options.appVer?{appVer:this.options.appVer}:{},...this.options.release?{release:this.options.release}:{},...this.options.channel?{channel:this.options.channel}:{},sessionId:this.sessionId,...(x=(U=this.options).getUserId)!=null&&x.call(U)?{userId:this.options.getUserId()}:{},...(D=(C=this.options).getNet)!=null&&D.call(C)?{net:this.options.getNet()}:{},sdkVer:ie,...this.adapter.getPlatformVersion()?{platformVersion:this.adapter.getPlatformVersion()}:{}},device:i,...t?{session:{launchTime:this.launchTime,duration:Math.max(0,Math.round((Date.now()-this.launchTime)/1e3)),pageCount:this.pageCount}}:{},logs:this.logs.splice(0,g.PROTOCOL_LIMITS.maxBatch),...this.events.length?{events:this.events.splice(0,g.PROTOCOL_LIMITS.maxEventsPerBatch)}:{}}}fallbackDeviceId(){let t=this.adapter.getStorage("uni-log:did");return t||(t=`did-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,this.adapter.setStorage("uni-log:did",t)),t}send(t){return new Promise(e=>{let r=!1,i=s=>{r||(r=!0,clearTimeout(a),e(s))},a=setTimeout(()=>i(!1),8e3);try{this.adapter.request({url:`${this.options.serverUrl}${g.INGEST_PATH}`,data:t,header:{"Content-Type":"application/json"},success:s=>i(!!s&&s.statusCode>=200&&s.statusCode<300),fail:()=>i(!1)})}catch{i(!1)}})}safeStringify(t){let e=new WeakSet;return JSON.stringify(t,(r,i)=>{if(typeof i=="bigint")return i.toString();if(typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i})}persistPending(t){let e=this.adapter.getStorage(w),r=[];try{r=e?JSON.parse(e):[],Array.isArray(r)||(r=[])}catch{r=[]}r.push(...t),r.length>M&&(r=r.slice(-M));try{this.adapter.setStorage(w,this.safeStringify(r))}catch(i){this.options.debug&&console.warn("[uni-log] \u6682\u5B58\u5931\u8D25",i)}}async retryPending(){let t=this.adapter.getStorage(w);if(!t)return;this.adapter.setStorage(w,"");let e;try{e=JSON.parse(t)}catch{return}if(!(!Array.isArray(e)||e.length===0)){for(let r=0;r<e.length;r++)if(!await this.send(e[r])){this.persistPending(e.slice(r)),this.options.debug&&console.warn("[uni-log] \u7EED\u4F20\u5931\u8D25\uFF0C\u6682\u5B58\u5DF2\u8FD8\u539F");return}}}installErrorHooks(){this.adapter.onError(t=>{this.log("error",String(t),{stack:String(t)})}),this.adapter.onUnhandledRejection(t=>{var i;let e=t,r=(i=e==null?void 0:e.reason)!=null?i:t;this.log("error",String(r),{stack:r==null?void 0:r.stack})})}};var o=null;function se(n){return o==null||o.stop(),o=new P(n),o.start(),n.hookConsole!==!1&&q(),o}function ae(){return o}function ge(n,t,e){o==null||o.log(n,t,e)}var W={debug:(n,t)=>o==null?void 0:o.log("debug",n,t),info:(n,t)=>o==null?void 0:o.log("info",n,t),warn:(n,t)=>o==null?void 0:o.log("warn",n,t),error:(n,t)=>o==null?void 0:o.log("error",n,t)},H=new Set,G=!0;function le(n){G=n}function q(){let n={debug:"debug",log:"info",info:"info",warn:"warn",error:"error"},t=console;for(let[e,r]of Object.entries(n)){if(H.has(e))continue;let i=t[e];if(typeof i!="function")continue;let a=i.bind(console);t[e]=(...s)=>{G&&W[r](s.map(de).join(" ")),a(...s)},H.add(e)}}function de(n){if(typeof n=="string")return n;if(n instanceof Error)return n.stack||n.message;try{let t=JSON.stringify(n);return t===void 0?String(n):t}catch{return String(n)}}function ue(n,t){o==null||o.report(n,t)}function ce(n){o==null||o.setDeviceName(n)}async function he(){await(o==null?void 0:o.flush())}0&&(module.exports={flush,getClient,hookConsole,init,report,setConsoleReport,setDeviceName,ulog,ulogger});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var W=Object.create;var D=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var K=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty;var V=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var J=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of q(t))!$.call(n,i)&&i!==e&&D(n,i,{get:()=>t[i],enumerable:!(r=G(t,i))||r.enumerable});return n};var Y=(n,t,e)=>(e=n!=null?W(K(n)):{},J(t||!n||!n.__esModule?D(e,"default",{value:n,enumerable:!0}):e,n));var A=V(u=>{"use strict";Object.defineProperty(u,"__esModule",{value:!0});u.PROTOCOL_LIMITS=u.INGEST_PATH=u.LOG_LEVELS=void 0;u.LOG_LEVELS=["debug","info","warn","error","crash"];u.INGEST_PATH="/ingest/v1/logs";u.PROTOCOL_LIMITS={maxBatch:50,maxMsgLength:4e3,maxStackLength:8e3,maxEventsPerBatch:50,maxEventKeyLength:64,maxEventValLength:255,maxBodyBytes:512*1024}});var T=V(h=>{"use strict";var F=h&&h.__createBinding||(Object.create?(function(n,t,e,r){r===void 0&&(r=e);var i=Object.getOwnPropertyDescriptor(t,e);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(n,r,i)}):(function(n,t,e,r){r===void 0&&(r=e),n[r]=t[e]})),X=h&&h.__exportStar||function(n,t){for(var e in n)e!=="default"&&!Object.prototype.hasOwnProperty.call(t,e)&&F(t,n,e)};Object.defineProperty(h,"__esModule",{value:!0});X(A(),h)});var g=Y(T());function p(){let n=globalThis.uni;return n!=null?n:null}function z(){var n,t,e;try{let r=globalThis;return typeof r.getCurrentPages=="function"?r.getCurrentPages():typeof getCurrentPages=="function"?getCurrentPages():(e=(t=(n=r.uni)==null?void 0:n.getCurrentPages)==null?void 0:t.call(n))!=null?e:null}catch{return null}}function Q(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function P(n){return typeof n=="string"&&n.length>0?n:void 0}function Z(n){let t=l=>{var c;try{return(c=l==null?void 0:l())!=null?c:{}}catch{return{}}},e=t(n==null?void 0:n.getSystemInfoSync),r=t(n==null?void 0:n.getDeviceInfo),i=t(n==null?void 0:n.getAppBaseInfo),a=t(n==null?void 0:n.getWindowInfo);if(Object.keys(e).length===0&&Object.keys(r).length===0)return null;let s=(...l)=>l.map(P).find(Boolean),d=(...l)=>l.map(Q).find(c=>c!==void 0),y=s(r.deviceId,e.deviceId,e.deviceUUID),v=s(e.uniPlatform,e.platform,r.platform,r.uniPlatform);return!y||!v?null:{deviceId:y,platform:v,deviceName:s(r.deviceName,e.deviceName),model:s(r.deviceModel,e.deviceModel,e.model),vendor:s(r.deviceBrand,e.deviceBrand,e.brand),os:s(e.osVersion,e.system,r.osVersion,r.system),osVersion:s(e.osVersion,r.osVersion),osName:s(e.osName,r.osName,i.osName),net:s(e.networkType,e.netType),language:s(i.language,e.language),pixelRatio:d(a.pixelRatio,e.pixelRatio),windowWidth:d(a.windowWidth,e.windowWidth),windowHeight:d(a.windowHeight,e.windowHeight),screenWidth:d(a.screenWidth,e.screenWidth),screenHeight:d(a.screenHeight,e.screenHeight)}}function j(){return{request(n){var e;let t=p();if(!(t!=null&&t.request)){(e=n.fail)==null||e.call(n,{errMsg:"uni-log: uni.request \u4E0D\u53EF\u7528"});return}t.request({...n,method:"POST"})},getStorage(n){var t,e;try{let r=(e=(t=p())==null?void 0:t.getStorageSync)==null?void 0:e.call(t,n);return typeof r=="string"&&r.length>0?r:null}catch{return null}},setStorage(n,t){var e,r;try{(r=(e=p())==null?void 0:e.setStorageSync)==null||r.call(e,n,t)}catch{}},getDeviceInfo(){try{return Z(p())}catch{return null}},getCurrentPage(){var n;try{let t=z(),e=t==null?void 0:t[t.length-1];return(n=e==null?void 0:e.route)!=null?n:null}catch{return null}},getPlatformVersion(){let n=p(),t=r=>{var i,a;try{let s=r();return s&&(a=(i=P(s.hostVersion))!=null?i:P(s.version))!=null?a:null}catch{return null}},e=n!=null&&n.getAppBaseInfo?t(()=>n.getAppBaseInfo()):null;return e||(n!=null&&n.getSystemInfoSync?t(()=>n.getSystemInfoSync()):null)},onError(n){var t,e;try{(e=(t=p())==null?void 0:t.onError)==null||e.call(t,n)}catch{}},onUnhandledRejection(n){var t,e;try{(e=(t=p())==null?void 0:t.onUnhandledRejection)==null||e.call(t,n)}catch{}}}}var m="uni-log:pending",B=20,ee="0.1.1";function f(n,t){return n.length>t?n.slice(0,t):n}function S(n){let t=n==null?void 0:n.trim();return t?f(t,128):void 0}function te(n,t,e){var i;let r={t:Date.now(),lv:n,msg:f(t||"(empty)",g.PROTOCOL_LIMITS.maxMsgLength)};return e!=null&&e.stack&&(r.stack=f(e.stack,g.PROTOCOL_LIMITS.maxStackLength)),e!=null&&e.page&&(r.page=f(e.page,255)),e!=null&&e.extra&&(r.extra=e.extra),(i=e==null?void 0:e.tags)!=null&&i.length&&(r.tags=e.tags),r}var w=class{constructor(t,e=j()){this.ready=!1;this.logs=[];this.events=[];this.timer=null;this.flushingPromise=null;this.launchTime=Date.now();this.pageCount=0;this.lastPage=null;this.deviceInfo=null;this.deviceNameOverride=null;this.options=t,this.adapter=e,this.sessionId=`sess-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}start(){var e;if(this.ready)return;this.ready=!0;let t=Math.max(1e3,(e=this.options.flushInterval)!=null?e:1e4);this.timer=setInterval(()=>{this.flush().catch(()=>{})},t),this.retryPending().catch(()=>{}),this.options.collectErrors!==!1&&this.installErrorHooks(),this.samplePage()}stop(){this.ready=!1,this.timer&&(clearInterval(this.timer),this.timer=null)}log(t,e,r){if(!this.ready)return;let i=g.LOG_LEVELS.includes(t)?t:"info";this.samplePage();let a=this.adapter.getCurrentPage();this.logs.push(te(i,e,{...r,...a?{page:a}:{}})),this.logs.length>=g.PROTOCOL_LIMITS.maxBatch&&this.flush()}report(t,e){if(!this.ready||!t||t.length>g.PROTOCOL_LIMITS.maxEventKeyLength)return;this.samplePage();let r={t:Date.now(),ev:t};e&&(r.val=f(e,g.PROTOCOL_LIMITS.maxEventValLength));let i=this.adapter.getCurrentPage();i&&(r.page=i),this.events.push(r),this.events.length>=g.PROTOCOL_LIMITS.maxEventsPerBatch&&this.flush()}pageView(t){if(!this.ready)return;let e=t!=null?t:this.adapter.getCurrentPage();this.pageCount+=1,e&&(this.lastPage=e)}setDeviceName(t){let e=t.trim();this.deviceNameOverride=e?f(e,128):null}samplePage(){let t=this.adapter.getCurrentPage();t&&t!==this.lastPage&&(this.lastPage=t,this.pageCount+=1)}async flush(){if(!this.ready)return;if(this.flushingPromise)return this.flushingPromise;let t=async()=>{var r;let e;try{for(this.samplePage(),e=this.buildPayload(!0);;){if(!await this.send(e)){(e.logs.length||(r=e.events)!=null&&r.length)&&(this.persistPending([e]),this.options.debug&&console.warn("[uni-log] \u4E0A\u62A5\u5931\u8D25\uFF0C\u5DF2\u6682\u5B58\u5F85\u7EED\u4F20"));break}if(this.logs.length===0&&this.events.length===0)break;e=this.buildPayload(!1)}}catch(i){if(e)try{this.persistPending([e])}catch{}this.options.debug&&console.warn("[uni-log] flush \u5F02\u5E38",i)}finally{this.flushingPromise=null}};return this.flushingPromise=t(),this.flushingPromise}buildPayload(t){var s,d,y,v,l,c,b,k,I,L,E,R,_,N,O,U,x,C;let e=(s=this.deviceInfo)!=null?s:this.deviceInfo=this.adapter.getDeviceInfo(),r=(c=(l=(v=this.deviceNameOverride)!=null?v:S((y=(d=this.options).getDeviceName)==null?void 0:y.call(d)))!=null?l:S(this.options.deviceName))!=null?c:S(e==null?void 0:e.deviceName),i={deviceId:(b=e==null?void 0:e.deviceId)!=null?b:this.fallbackDeviceId(),platform:(k=e==null?void 0:e.platform)!=null?k:"unknown",...r?{deviceName:r}:{},...e!=null&&e.model?{model:e.model}:{},...e!=null&&e.vendor?{vendor:e.vendor}:{},...e!=null&&e.os?{os:e.os}:{},...e!=null&&e.osVersion?{osVersion:e.osVersion}:{},...e!=null&&e.osName?{osName:e.osName}:{},...((E=e==null?void 0:e.net)!=null?E:(L=(I=this.options).getNet)!=null&&L.call(I))?{net:(N=e==null?void 0:e.net)!=null?N:(_=(R=this.options).getNet)==null?void 0:_.call(R)}:{},...e!=null&&e.language?{language:e.language}:{},...e!=null&&e.pixelRatio?{pixelRatio:e.pixelRatio}:{},...e!=null&&e.windowWidth?{windowWidth:e.windowWidth}:{},...e!=null&&e.windowHeight?{windowHeight:e.windowHeight}:{},...e!=null&&e.screenWidth?{screenWidth:e.screenWidth}:{},...e!=null&&e.screenHeight?{screenHeight:e.screenHeight}:{}};return{header:{appKey:this.options.appKey,...this.options.appVer?{appVer:this.options.appVer}:{},...this.options.release?{release:this.options.release}:{},...this.options.channel?{channel:this.options.channel}:{},sessionId:this.sessionId,...(U=(O=this.options).getUserId)!=null&&U.call(O)?{userId:this.options.getUserId()}:{},...(C=(x=this.options).getNet)!=null&&C.call(x)?{net:this.options.getNet()}:{},sdkVer:ee,...this.adapter.getPlatformVersion()?{platformVersion:this.adapter.getPlatformVersion()}:{}},device:i,...t?{session:{launchTime:this.launchTime,duration:Math.max(0,Math.round((Date.now()-this.launchTime)/1e3)),pageCount:this.pageCount}}:{},logs:this.logs.splice(0,g.PROTOCOL_LIMITS.maxBatch),...this.events.length?{events:this.events.splice(0,g.PROTOCOL_LIMITS.maxEventsPerBatch)}:{}}}fallbackDeviceId(){let t=this.adapter.getStorage("uni-log:did");return t||(t=`did-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,this.adapter.setStorage("uni-log:did",t)),t}send(t){return new Promise(e=>{let r=!1,i=s=>{r||(r=!0,clearTimeout(a),e(s))},a=setTimeout(()=>i(!1),8e3);try{this.adapter.request({url:`${this.options.serverUrl}${g.INGEST_PATH}`,data:t,header:{"Content-Type":"application/json"},success:s=>i(!!s&&s.statusCode>=200&&s.statusCode<300),fail:()=>i(!1)})}catch{i(!1)}})}safeStringify(t){let e=new WeakSet;return JSON.stringify(t,(r,i)=>{if(typeof i=="bigint")return i.toString();if(typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i})}persistPending(t){let e=this.adapter.getStorage(m),r=[];try{r=e?JSON.parse(e):[],Array.isArray(r)||(r=[])}catch{r=[]}r.push(...t),r.length>B&&(r=r.slice(-B));try{this.adapter.setStorage(m,this.safeStringify(r))}catch(i){this.options.debug&&console.warn("[uni-log] \u6682\u5B58\u5931\u8D25",i)}}async retryPending(){let t=this.adapter.getStorage(m);if(!t)return;this.adapter.setStorage(m,"");let e;try{e=JSON.parse(t)}catch{return}if(!(!Array.isArray(e)||e.length===0)){for(let r=0;r<e.length;r++)if(!await this.send(e[r])){this.persistPending(e.slice(r)),this.options.debug&&console.warn("[uni-log] \u7EED\u4F20\u5931\u8D25\uFF0C\u6682\u5B58\u5DF2\u8FD8\u539F");return}}}installErrorHooks(){this.adapter.onError(t=>{this.log("error",String(t),{stack:String(t)})}),this.adapter.onUnhandledRejection(t=>{var i;let e=t,r=(i=e==null?void 0:e.reason)!=null?i:t;this.log("error",String(r),{stack:r==null?void 0:r.stack})})}};var o=null;function ce(n){return o==null||o.stop(),o=new w(n),o.start(),n.hookConsole!==!1&&re(),o}function he(){return o}function pe(n,t,e){o==null||o.log(n,t,e)}var ne={debug:(n,t)=>o==null?void 0:o.log("debug",n,t),info:(n,t)=>o==null?void 0:o.log("info",n,t),warn:(n,t)=>o==null?void 0:o.log("warn",n,t),error:(n,t)=>o==null?void 0:o.log("error",n,t)},M=new Set,H=!0;function fe(n){H=n}function re(){let n={debug:"debug",log:"info",info:"info",warn:"warn",error:"error"},t=console;for(let[e,r]of Object.entries(n)){if(M.has(e))continue;let i=t[e];if(typeof i!="function")continue;let a=i.bind(console);t[e]=(...s)=>{H&&ne[r](s.map(ie).join(" ")),a(...s)},M.add(e)}}function ie(n){if(typeof n=="string")return n;if(n instanceof Error)return n.stack||n.message;try{let t=JSON.stringify(n);return t===void 0?String(n):t}catch{return String(n)}}function ye(n,t){o==null||o.report(n,t)}function ve(n){o==null||o.setDeviceName(n)}async function me(){await(o==null?void 0:o.flush())}export{me as flush,he as getClient,re as hookConsole,ce as init,ye as report,fe as setConsoleReport,ve as setDeviceName,pe as ulog,ne as ulogger};
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "uni-log-sdk",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"private": false,
|
|
5
|
+
"description": "uni-app / uni-app x 日志上报 SDK:console、JS 错误、自定义事件与设备信息批量上报",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"uni-app",
|
|
8
|
+
"uni-app x",
|
|
9
|
+
"uni_modules",
|
|
10
|
+
"日志",
|
|
11
|
+
"埋点",
|
|
12
|
+
"sdk"
|
|
13
|
+
],
|
|
14
|
+
"license": "UNLICENSED",
|
|
15
|
+
"main": "dist/index.js",
|
|
16
|
+
"module": "dist/index.mjs",
|
|
17
|
+
"types": "dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"import": "./dist/index.mjs",
|
|
22
|
+
"require": "./dist/index.js"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"bin": {
|
|
26
|
+
"uni-log": "bin/uni-log.mjs"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"dist",
|
|
30
|
+
"uni_modules",
|
|
31
|
+
"bin",
|
|
32
|
+
"scripts",
|
|
33
|
+
"README.md"
|
|
34
|
+
],
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=18"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"build": "tsup && node scripts/build-uni-module.mjs",
|
|
40
|
+
"test": "vitest run",
|
|
41
|
+
"test:watch": "vitest",
|
|
42
|
+
"postinstall": "node scripts/postinstall.mjs",
|
|
43
|
+
"prepublishOnly": "npm run build && npm test"
|
|
44
|
+
},
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"registry": "https://registry.npmjs.org/"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@uni-log/shared": "workspace:*",
|
|
50
|
+
"tsup": "^8.0.0",
|
|
51
|
+
"typescript": "^5.6.0",
|
|
52
|
+
"vitest": "^3.0.0"
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 由 tsup 产物生成 uni_modules 形态:
|
|
3
|
+
* dist/index.mjs -> uni_modules/uni-log/index.js
|
|
4
|
+
* 同时写入 uni_modules 插件清单(HBuilderX 需要 id/displayName/version)。
|
|
5
|
+
* 在 packages/sdk 下执行 `npm run build` 时自动运行。
|
|
6
|
+
*/
|
|
7
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
8
|
+
import { dirname, join } from 'node:path'
|
|
9
|
+
import { fileURLToPath } from 'node:url'
|
|
10
|
+
|
|
11
|
+
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
|
|
12
|
+
const pkg = JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8'))
|
|
13
|
+
const pluginDir = join(pkgRoot, 'uni_modules', 'uni-log')
|
|
14
|
+
|
|
15
|
+
rmSync(pluginDir, { recursive: true, force: true })
|
|
16
|
+
mkdirSync(pluginDir, { recursive: true })
|
|
17
|
+
copyFileSync(join(pkgRoot, 'dist', 'index.mjs'), join(pluginDir, 'index.js'))
|
|
18
|
+
|
|
19
|
+
const pluginPkg = {
|
|
20
|
+
id: 'uni-log',
|
|
21
|
+
displayName: 'uni-log 日志上报',
|
|
22
|
+
version: pkg.version,
|
|
23
|
+
description: pkg.description,
|
|
24
|
+
keywords: pkg.keywords ?? [],
|
|
25
|
+
}
|
|
26
|
+
writeFileSync(join(pluginDir, 'package.json'), `${JSON.stringify(pluginPkg, null, 4)}\n`)
|
|
27
|
+
|
|
28
|
+
// HBuilderX 插件详情页展示 readme.md(小写文件名是 uni_modules 约定)
|
|
29
|
+
const readme = join(pkgRoot, 'README.md')
|
|
30
|
+
if (existsSync(readme)) copyFileSync(readme, join(pluginDir, 'readme.md'))
|
|
31
|
+
|
|
32
|
+
console.log(`[uni-log] uni_modules 已生成:${pluginDir}(v${pkg.version})`)
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* npm install 后的自动同步:
|
|
3
|
+
* 探测宿主工程里是否只有一个 uni-app 工程,是则把 uni_modules/uni-log 物化过去。
|
|
4
|
+
*
|
|
5
|
+
* 设计约束:
|
|
6
|
+
* - 只在本包作为依赖安装时执行(包位于 node_modules 下);本仓库源码开发不触发
|
|
7
|
+
* - 找不到工程 / 找到多个工程时不写文件,只提示,避免写错目录
|
|
8
|
+
* - 目标版本不低于当前包版本时跳过,避免降级覆盖
|
|
9
|
+
* - UNI_LOG_AUTO_SYNC=0 可关闭
|
|
10
|
+
*/
|
|
11
|
+
import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync } from 'node:fs'
|
|
12
|
+
import { dirname, join, resolve, sep } from 'node:path'
|
|
13
|
+
import { fileURLToPath } from 'node:url'
|
|
14
|
+
|
|
15
|
+
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
|
|
16
|
+
const pkg = JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8'))
|
|
17
|
+
|
|
18
|
+
function info(msg) {
|
|
19
|
+
console.log(`[uni-log] ${msg}`)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 本仓库源码目录(packages/sdk)不自动同步,避免 pnpm install 时改动 demo 工程 */
|
|
23
|
+
if (!pkgRoot.split(sep).includes('node_modules')) process.exit(0)
|
|
24
|
+
|
|
25
|
+
if (process.env.UNI_LOG_AUTO_SYNC === '0') {
|
|
26
|
+
info('UNI_LOG_AUTO_SYNC=0,跳过自动同步')
|
|
27
|
+
process.exit(0)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** uni-app / uni-app x 工程根:根目录或 src 下同时有 manifest.json 与 pages.json */
|
|
31
|
+
function isUniAppRoot(dir) {
|
|
32
|
+
const has = (d) => existsSync(join(d, 'manifest.json')) && existsSync(join(d, 'pages.json'))
|
|
33
|
+
return has(dir) || has(join(dir, 'src'))
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 从起始目录向下最多找 2 层,遇到工程根就不再深入 */
|
|
37
|
+
function findProjects(startDir) {
|
|
38
|
+
const found = new Set()
|
|
39
|
+
const queue = [{ dir: startDir, depth: 0 }]
|
|
40
|
+
while (queue.length > 0) {
|
|
41
|
+
const { dir, depth } = queue.shift()
|
|
42
|
+
if (isUniAppRoot(dir)) {
|
|
43
|
+
found.add(dir)
|
|
44
|
+
continue
|
|
45
|
+
}
|
|
46
|
+
if (depth >= 2) continue
|
|
47
|
+
let entries = []
|
|
48
|
+
try {
|
|
49
|
+
entries = readdirSync(dir, { withFileTypes: true })
|
|
50
|
+
} catch {
|
|
51
|
+
continue
|
|
52
|
+
}
|
|
53
|
+
for (const entry of entries) {
|
|
54
|
+
if (!entry.isDirectory()) continue
|
|
55
|
+
if (['node_modules', 'unpackage', 'dist', '.git', '.hbuilderx'].includes(entry.name)) continue
|
|
56
|
+
if (entry.name.startsWith('.')) continue
|
|
57
|
+
queue.push({ dir: join(dir, entry.name), depth: depth + 1 })
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return [...found]
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function parseVersion(v) {
|
|
64
|
+
return String(v)
|
|
65
|
+
.split('.')
|
|
66
|
+
.map((n) => Number.parseInt(n, 10) || 0)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function compareVersion(a, b) {
|
|
70
|
+
const va = parseVersion(a)
|
|
71
|
+
const vb = parseVersion(b)
|
|
72
|
+
for (let i = 0; i < Math.max(va.length, vb.length); i++) {
|
|
73
|
+
const diff = (va[i] ?? 0) - (vb[i] ?? 0)
|
|
74
|
+
if (diff !== 0) return diff
|
|
75
|
+
}
|
|
76
|
+
return 0
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// npm 会把「执行安装命令时所在目录」放到 INIT_CWD;pnpm 同样兼容
|
|
80
|
+
const starts = [...new Set([process.env.INIT_CWD, process.cwd()].filter(Boolean).map((p) => resolve(p)))]
|
|
81
|
+
.filter((dir) => !dir.split(sep).includes('node_modules'))
|
|
82
|
+
|
|
83
|
+
const projects = [...new Set(starts.flatMap(findProjects))]
|
|
84
|
+
|
|
85
|
+
if (projects.length === 0) {
|
|
86
|
+
// 不是 uni-app 工程(或宿主工程结构无法识别):静默退出,不影响安装
|
|
87
|
+
process.exit(0)
|
|
88
|
+
}
|
|
89
|
+
if (projects.length > 1) {
|
|
90
|
+
info(`检测到 ${projects.length} 个 uni-app 工程,已跳过自动同步:`)
|
|
91
|
+
for (const p of projects) info(` - ${p}`)
|
|
92
|
+
info('请进入目标工程执行:npx uni-log sync --target <工程根目录>')
|
|
93
|
+
process.exit(0)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const project = projects[0]
|
|
97
|
+
const end = join(project, 'uni_modules', 'uni-log', 'package.json')
|
|
98
|
+
if (existsSync(end)) {
|
|
99
|
+
try {
|
|
100
|
+
const installed = JSON.parse(readFileSync(end, 'utf8'))
|
|
101
|
+
if (compareVersion(installed.version, pkg.version) >= 0) {
|
|
102
|
+
info(`uni_modules/uni-log 已是 v${installed.version},跳过同步`)
|
|
103
|
+
process.exit(0)
|
|
104
|
+
}
|
|
105
|
+
} catch {
|
|
106
|
+
// 已有的 package.json 损坏时直接覆盖
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const src = join(pkgRoot, 'uni_modules', 'uni-log')
|
|
111
|
+
if (!existsSync(join(src, 'index.js'))) {
|
|
112
|
+
info('包内缺少 uni_modules/uni-log,跳过自动同步(请升级 SDK 或手动执行 npx uni-log sync)')
|
|
113
|
+
process.exit(0)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const dest = join(project, 'uni_modules', 'uni-log')
|
|
117
|
+
mkdirSync(dirname(dest), { recursive: true })
|
|
118
|
+
cpSync(src, dest, { recursive: true, force: true })
|
|
119
|
+
|
|
120
|
+
info(`v${pkg.version} 已自动同步到 ${dest}`)
|
|
121
|
+
info('引用方式:import { init } from "@/uni_modules/uni-log"')
|
|
122
|
+
info('关闭自动同步:设置环境变量 UNI_LOG_AUTO_SYNC=0')
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var W=Object.create;var D=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var K=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty;var V=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var J=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of q(t))!$.call(n,i)&&i!==e&&D(n,i,{get:()=>t[i],enumerable:!(r=G(t,i))||r.enumerable});return n};var Y=(n,t,e)=>(e=n!=null?W(K(n)):{},J(t||!n||!n.__esModule?D(e,"default",{value:n,enumerable:!0}):e,n));var A=V(u=>{"use strict";Object.defineProperty(u,"__esModule",{value:!0});u.PROTOCOL_LIMITS=u.INGEST_PATH=u.LOG_LEVELS=void 0;u.LOG_LEVELS=["debug","info","warn","error","crash"];u.INGEST_PATH="/ingest/v1/logs";u.PROTOCOL_LIMITS={maxBatch:50,maxMsgLength:4e3,maxStackLength:8e3,maxEventsPerBatch:50,maxEventKeyLength:64,maxEventValLength:255,maxBodyBytes:512*1024}});var T=V(h=>{"use strict";var F=h&&h.__createBinding||(Object.create?(function(n,t,e,r){r===void 0&&(r=e);var i=Object.getOwnPropertyDescriptor(t,e);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(n,r,i)}):(function(n,t,e,r){r===void 0&&(r=e),n[r]=t[e]})),X=h&&h.__exportStar||function(n,t){for(var e in n)e!=="default"&&!Object.prototype.hasOwnProperty.call(t,e)&&F(t,n,e)};Object.defineProperty(h,"__esModule",{value:!0});X(A(),h)});var g=Y(T());function p(){let n=globalThis.uni;return n!=null?n:null}function z(){var n,t,e;try{let r=globalThis;return typeof r.getCurrentPages=="function"?r.getCurrentPages():typeof getCurrentPages=="function"?getCurrentPages():(e=(t=(n=r.uni)==null?void 0:n.getCurrentPages)==null?void 0:t.call(n))!=null?e:null}catch{return null}}function Q(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function P(n){return typeof n=="string"&&n.length>0?n:void 0}function Z(n){let t=l=>{var c;try{return(c=l==null?void 0:l())!=null?c:{}}catch{return{}}},e=t(n==null?void 0:n.getSystemInfoSync),r=t(n==null?void 0:n.getDeviceInfo),i=t(n==null?void 0:n.getAppBaseInfo),a=t(n==null?void 0:n.getWindowInfo);if(Object.keys(e).length===0&&Object.keys(r).length===0)return null;let s=(...l)=>l.map(P).find(Boolean),d=(...l)=>l.map(Q).find(c=>c!==void 0),y=s(r.deviceId,e.deviceId,e.deviceUUID),v=s(e.uniPlatform,e.platform,r.platform,r.uniPlatform);return!y||!v?null:{deviceId:y,platform:v,deviceName:s(r.deviceName,e.deviceName),model:s(r.deviceModel,e.deviceModel,e.model),vendor:s(r.deviceBrand,e.deviceBrand,e.brand),os:s(e.osVersion,e.system,r.osVersion,r.system),osVersion:s(e.osVersion,r.osVersion),osName:s(e.osName,r.osName,i.osName),net:s(e.networkType,e.netType),language:s(i.language,e.language),pixelRatio:d(a.pixelRatio,e.pixelRatio),windowWidth:d(a.windowWidth,e.windowWidth),windowHeight:d(a.windowHeight,e.windowHeight),screenWidth:d(a.screenWidth,e.screenWidth),screenHeight:d(a.screenHeight,e.screenHeight)}}function j(){return{request(n){var e;let t=p();if(!(t!=null&&t.request)){(e=n.fail)==null||e.call(n,{errMsg:"uni-log: uni.request \u4E0D\u53EF\u7528"});return}t.request({...n,method:"POST"})},getStorage(n){var t,e;try{let r=(e=(t=p())==null?void 0:t.getStorageSync)==null?void 0:e.call(t,n);return typeof r=="string"&&r.length>0?r:null}catch{return null}},setStorage(n,t){var e,r;try{(r=(e=p())==null?void 0:e.setStorageSync)==null||r.call(e,n,t)}catch{}},getDeviceInfo(){try{return Z(p())}catch{return null}},getCurrentPage(){var n;try{let t=z(),e=t==null?void 0:t[t.length-1];return(n=e==null?void 0:e.route)!=null?n:null}catch{return null}},getPlatformVersion(){let n=p(),t=r=>{var i,a;try{let s=r();return s&&(a=(i=P(s.hostVersion))!=null?i:P(s.version))!=null?a:null}catch{return null}},e=n!=null&&n.getAppBaseInfo?t(()=>n.getAppBaseInfo()):null;return e||(n!=null&&n.getSystemInfoSync?t(()=>n.getSystemInfoSync()):null)},onError(n){var t,e;try{(e=(t=p())==null?void 0:t.onError)==null||e.call(t,n)}catch{}},onUnhandledRejection(n){var t,e;try{(e=(t=p())==null?void 0:t.onUnhandledRejection)==null||e.call(t,n)}catch{}}}}var m="uni-log:pending",B=20,ee="0.1.1";function f(n,t){return n.length>t?n.slice(0,t):n}function S(n){let t=n==null?void 0:n.trim();return t?f(t,128):void 0}function te(n,t,e){var i;let r={t:Date.now(),lv:n,msg:f(t||"(empty)",g.PROTOCOL_LIMITS.maxMsgLength)};return e!=null&&e.stack&&(r.stack=f(e.stack,g.PROTOCOL_LIMITS.maxStackLength)),e!=null&&e.page&&(r.page=f(e.page,255)),e!=null&&e.extra&&(r.extra=e.extra),(i=e==null?void 0:e.tags)!=null&&i.length&&(r.tags=e.tags),r}var w=class{constructor(t,e=j()){this.ready=!1;this.logs=[];this.events=[];this.timer=null;this.flushingPromise=null;this.launchTime=Date.now();this.pageCount=0;this.lastPage=null;this.deviceInfo=null;this.deviceNameOverride=null;this.options=t,this.adapter=e,this.sessionId=`sess-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}start(){var e;if(this.ready)return;this.ready=!0;let t=Math.max(1e3,(e=this.options.flushInterval)!=null?e:1e4);this.timer=setInterval(()=>{this.flush().catch(()=>{})},t),this.retryPending().catch(()=>{}),this.options.collectErrors!==!1&&this.installErrorHooks(),this.samplePage()}stop(){this.ready=!1,this.timer&&(clearInterval(this.timer),this.timer=null)}log(t,e,r){if(!this.ready)return;let i=g.LOG_LEVELS.includes(t)?t:"info";this.samplePage();let a=this.adapter.getCurrentPage();this.logs.push(te(i,e,{...r,...a?{page:a}:{}})),this.logs.length>=g.PROTOCOL_LIMITS.maxBatch&&this.flush()}report(t,e){if(!this.ready||!t||t.length>g.PROTOCOL_LIMITS.maxEventKeyLength)return;this.samplePage();let r={t:Date.now(),ev:t};e&&(r.val=f(e,g.PROTOCOL_LIMITS.maxEventValLength));let i=this.adapter.getCurrentPage();i&&(r.page=i),this.events.push(r),this.events.length>=g.PROTOCOL_LIMITS.maxEventsPerBatch&&this.flush()}pageView(t){if(!this.ready)return;let e=t!=null?t:this.adapter.getCurrentPage();this.pageCount+=1,e&&(this.lastPage=e)}setDeviceName(t){let e=t.trim();this.deviceNameOverride=e?f(e,128):null}samplePage(){let t=this.adapter.getCurrentPage();t&&t!==this.lastPage&&(this.lastPage=t,this.pageCount+=1)}async flush(){if(!this.ready)return;if(this.flushingPromise)return this.flushingPromise;let t=async()=>{var r;let e;try{for(this.samplePage(),e=this.buildPayload(!0);;){if(!await this.send(e)){(e.logs.length||(r=e.events)!=null&&r.length)&&(this.persistPending([e]),this.options.debug&&console.warn("[uni-log] \u4E0A\u62A5\u5931\u8D25\uFF0C\u5DF2\u6682\u5B58\u5F85\u7EED\u4F20"));break}if(this.logs.length===0&&this.events.length===0)break;e=this.buildPayload(!1)}}catch(i){if(e)try{this.persistPending([e])}catch{}this.options.debug&&console.warn("[uni-log] flush \u5F02\u5E38",i)}finally{this.flushingPromise=null}};return this.flushingPromise=t(),this.flushingPromise}buildPayload(t){var s,d,y,v,l,c,b,k,I,L,E,R,_,N,O,U,x,C;let e=(s=this.deviceInfo)!=null?s:this.deviceInfo=this.adapter.getDeviceInfo(),r=(c=(l=(v=this.deviceNameOverride)!=null?v:S((y=(d=this.options).getDeviceName)==null?void 0:y.call(d)))!=null?l:S(this.options.deviceName))!=null?c:S(e==null?void 0:e.deviceName),i={deviceId:(b=e==null?void 0:e.deviceId)!=null?b:this.fallbackDeviceId(),platform:(k=e==null?void 0:e.platform)!=null?k:"unknown",...r?{deviceName:r}:{},...e!=null&&e.model?{model:e.model}:{},...e!=null&&e.vendor?{vendor:e.vendor}:{},...e!=null&&e.os?{os:e.os}:{},...e!=null&&e.osVersion?{osVersion:e.osVersion}:{},...e!=null&&e.osName?{osName:e.osName}:{},...((E=e==null?void 0:e.net)!=null?E:(L=(I=this.options).getNet)!=null&&L.call(I))?{net:(N=e==null?void 0:e.net)!=null?N:(_=(R=this.options).getNet)==null?void 0:_.call(R)}:{},...e!=null&&e.language?{language:e.language}:{},...e!=null&&e.pixelRatio?{pixelRatio:e.pixelRatio}:{},...e!=null&&e.windowWidth?{windowWidth:e.windowWidth}:{},...e!=null&&e.windowHeight?{windowHeight:e.windowHeight}:{},...e!=null&&e.screenWidth?{screenWidth:e.screenWidth}:{},...e!=null&&e.screenHeight?{screenHeight:e.screenHeight}:{}};return{header:{appKey:this.options.appKey,...this.options.appVer?{appVer:this.options.appVer}:{},...this.options.release?{release:this.options.release}:{},...this.options.channel?{channel:this.options.channel}:{},sessionId:this.sessionId,...(U=(O=this.options).getUserId)!=null&&U.call(O)?{userId:this.options.getUserId()}:{},...(C=(x=this.options).getNet)!=null&&C.call(x)?{net:this.options.getNet()}:{},sdkVer:ee,...this.adapter.getPlatformVersion()?{platformVersion:this.adapter.getPlatformVersion()}:{}},device:i,...t?{session:{launchTime:this.launchTime,duration:Math.max(0,Math.round((Date.now()-this.launchTime)/1e3)),pageCount:this.pageCount}}:{},logs:this.logs.splice(0,g.PROTOCOL_LIMITS.maxBatch),...this.events.length?{events:this.events.splice(0,g.PROTOCOL_LIMITS.maxEventsPerBatch)}:{}}}fallbackDeviceId(){let t=this.adapter.getStorage("uni-log:did");return t||(t=`did-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,this.adapter.setStorage("uni-log:did",t)),t}send(t){return new Promise(e=>{let r=!1,i=s=>{r||(r=!0,clearTimeout(a),e(s))},a=setTimeout(()=>i(!1),8e3);try{this.adapter.request({url:`${this.options.serverUrl}${g.INGEST_PATH}`,data:t,header:{"Content-Type":"application/json"},success:s=>i(!!s&&s.statusCode>=200&&s.statusCode<300),fail:()=>i(!1)})}catch{i(!1)}})}safeStringify(t){let e=new WeakSet;return JSON.stringify(t,(r,i)=>{if(typeof i=="bigint")return i.toString();if(typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i})}persistPending(t){let e=this.adapter.getStorage(m),r=[];try{r=e?JSON.parse(e):[],Array.isArray(r)||(r=[])}catch{r=[]}r.push(...t),r.length>B&&(r=r.slice(-B));try{this.adapter.setStorage(m,this.safeStringify(r))}catch(i){this.options.debug&&console.warn("[uni-log] \u6682\u5B58\u5931\u8D25",i)}}async retryPending(){let t=this.adapter.getStorage(m);if(!t)return;this.adapter.setStorage(m,"");let e;try{e=JSON.parse(t)}catch{return}if(!(!Array.isArray(e)||e.length===0)){for(let r=0;r<e.length;r++)if(!await this.send(e[r])){this.persistPending(e.slice(r)),this.options.debug&&console.warn("[uni-log] \u7EED\u4F20\u5931\u8D25\uFF0C\u6682\u5B58\u5DF2\u8FD8\u539F");return}}}installErrorHooks(){this.adapter.onError(t=>{this.log("error",String(t),{stack:String(t)})}),this.adapter.onUnhandledRejection(t=>{var i;let e=t,r=(i=e==null?void 0:e.reason)!=null?i:t;this.log("error",String(r),{stack:r==null?void 0:r.stack})})}};var o=null;function ce(n){return o==null||o.stop(),o=new w(n),o.start(),n.hookConsole!==!1&&re(),o}function he(){return o}function pe(n,t,e){o==null||o.log(n,t,e)}var ne={debug:(n,t)=>o==null?void 0:o.log("debug",n,t),info:(n,t)=>o==null?void 0:o.log("info",n,t),warn:(n,t)=>o==null?void 0:o.log("warn",n,t),error:(n,t)=>o==null?void 0:o.log("error",n,t)},M=new Set,H=!0;function fe(n){H=n}function re(){let n={debug:"debug",log:"info",info:"info",warn:"warn",error:"error"},t=console;for(let[e,r]of Object.entries(n)){if(M.has(e))continue;let i=t[e];if(typeof i!="function")continue;let a=i.bind(console);t[e]=(...s)=>{H&&ne[r](s.map(ie).join(" ")),a(...s)},M.add(e)}}function ie(n){if(typeof n=="string")return n;if(n instanceof Error)return n.stack||n.message;try{let t=JSON.stringify(n);return t===void 0?String(n):t}catch{return String(n)}}function ye(n,t){o==null||o.report(n,t)}function ve(n){o==null||o.setDeviceName(n)}async function me(){await(o==null?void 0:o.flush())}export{me as flush,he as getClient,re as hookConsole,ce as init,ye as report,fe as setConsoleReport,ve as setDeviceName,pe as ulog,ne as ulogger};
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# uni-log-sdk
|
|
2
|
+
|
|
3
|
+
uni-app / uni-app x 日志上报 SDK:console、JS 错误、自定义事件、设备与会话心跳,批量上报到自建 uni-log 服务端。
|
|
4
|
+
|
|
5
|
+
- 纯 JS、无外部运行时依赖(shared 协议已内联),可在 uni-app x 蒸汽模式、普通 uni-app、H5、小程序中运行
|
|
6
|
+
- 默认 10s 批量上报,满 50 条立即发送;发送失败写入本地暂存,冷启动自动续传
|
|
7
|
+
- 提供 uni_modules 形态,HBuilderX 工程可直接引用
|
|
8
|
+
|
|
9
|
+
## 安装
|
|
10
|
+
|
|
11
|
+
### 方式一:uni_modules(推荐,HBuilderX / CLI 通用)
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install -D uni-log-sdk
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
安装后 `postinstall` 会自动探测宿主工程:**若仓库里只有一个 uni-app 工程**,直接把 `uni_modules/uni-log` 物化到工程根,无需额外命令。
|
|
18
|
+
|
|
19
|
+
自动同步未生效时,按原因处理:
|
|
20
|
+
|
|
21
|
+
| 原因 | 处理 |
|
|
22
|
+
| --- | --- |
|
|
23
|
+
| pnpm 10+ 默认禁用依赖的 `postinstall` | 执行 `pnpm approve-builds` 勾选 `uni-log-sdk`,或在 `pnpm-workspace.yaml` 配 `allowBuilds`(旧版 pnpm 10 用 `onlyBuiltDependencies`),或手动执行 `npx uni-log sync` |
|
|
24
|
+
| npm 11.19+ 提示 install scripts 未审批 | 如脚本被拦截,执行 `npm install-scripts approve uni-log-sdk` 后重装;未被拦截时警告可忽略 |
|
|
25
|
+
| 仓库里有多个 uni-app 工程 | 自动同步会跳过并列出候选目录,执行 `npx uni-log sync --target <工程根>` |
|
|
26
|
+
| 安装时带了 `--ignore-scripts` | 手动执行 `npx uni-log sync` |
|
|
27
|
+
| 想关闭自动同步 | 安装时设置环境变量 `UNI_LOG_AUTO_SYNC=0` |
|
|
28
|
+
|
|
29
|
+
```yaml
|
|
30
|
+
# pnpm-workspace.yaml(pnpm 10+)
|
|
31
|
+
allowBuilds:
|
|
32
|
+
'uni-log-sdk': true
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```json
|
|
36
|
+
// package.json(pnpm 10 的 pnpm approve-builds 也会写入这里)
|
|
37
|
+
"pnpm": { "onlyBuiltDependencies": ["uni-log-sdk"] }
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
同步完成后在入口引用:
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import { init } from '@/uni_modules/uni-log'
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
升级 SDK 后重新 `npm install` 即可,`postinstall` 会覆盖旧版本;也可随时手动执行 `npx uni-log sync`。
|
|
47
|
+
|
|
48
|
+
### 方式二:直接 import(CLI / Vite 工程)
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
npm install uni-log-sdk
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
import { init } from 'uni-log-sdk'
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## 初始化
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
// App.vue / App.uvue 的 onLaunch
|
|
62
|
+
import { init } from '@/uni_modules/uni-log'
|
|
63
|
+
|
|
64
|
+
init({
|
|
65
|
+
serverUrl: 'https://log.example.com', // 不带尾斜杠;App 真机不要用 localhost
|
|
66
|
+
appKey: '<看板「应用管理」分配>',
|
|
67
|
+
appVer: '1.0.0',
|
|
68
|
+
release: 'release',
|
|
69
|
+
channel: 'default',
|
|
70
|
+
})
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### 选项
|
|
74
|
+
|
|
75
|
+
| 选项 | 类型 | 默认 | 说明 |
|
|
76
|
+
| --- | --- | --- | --- |
|
|
77
|
+
| `serverUrl` | string | 必填 | 服务端地址,上报路径为 `/ingest/v1/logs` |
|
|
78
|
+
| `appKey` | string | 必填 | 应用 Key,看板「应用管理」获取 |
|
|
79
|
+
| `appVer` | string | - | 业务应用版本号 |
|
|
80
|
+
| `release` | string | - | 发布渠道/环境标识 |
|
|
81
|
+
| `channel` | string | - | 渠道 code / 小程序场景值 |
|
|
82
|
+
| `deviceName` | string | - | 设备名称(给人看的) |
|
|
83
|
+
| `getDeviceName` | `() => string` | - | 动态设备名称,优先级高于 `deviceName` |
|
|
84
|
+
| `getUserId` | `() => string` | - | 业务用户标识 |
|
|
85
|
+
| `getNet` | `() => string` | - | 网络类型 |
|
|
86
|
+
| `flushInterval` | number | `10000` | 上报间隔(毫秒) |
|
|
87
|
+
| `collectErrors` | boolean | `true` | 自动捕获 `uni.onError` / `onUnhandledRejection` |
|
|
88
|
+
| `hookConsole` | boolean | `true` | 运行时劫持 `console.*` 并上报 |
|
|
89
|
+
| `debug` | boolean | `false` | 打印 SDK 内部日志 |
|
|
90
|
+
|
|
91
|
+
## 常用 API
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import {
|
|
95
|
+
ulog,
|
|
96
|
+
ulogger,
|
|
97
|
+
report,
|
|
98
|
+
flush,
|
|
99
|
+
setDeviceName,
|
|
100
|
+
setConsoleReport,
|
|
101
|
+
getClient,
|
|
102
|
+
} from '@/uni_modules/uni-log'
|
|
103
|
+
|
|
104
|
+
ulog('info', '自定义日志', { page: 'pages/index/index', extra: { id: 1 } })
|
|
105
|
+
ulogger.warn('等价于 console.warn 的上报入口')
|
|
106
|
+
report('pay_success', 'order-123') // 自定义事件(对标 uni.report)
|
|
107
|
+
getClient()?.pageView() // 精确 PV,建议在页面 onShow 调用
|
|
108
|
+
setDeviceName('Jane 的 iPhone') // 传空串恢复服务端兜底
|
|
109
|
+
setConsoleReport(false) // 关闭 console.* 上报(保留原生打印),避免拦截器递归
|
|
110
|
+
await flush() // 应用退后台/页面隐藏时可主动上报
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## 注意事项
|
|
114
|
+
|
|
115
|
+
- `serverUrl` 不要带尾斜杠;App 真机需用局域网 IP 或 HTTPS 域名,Android 9+ 默认禁止明文 HTTP。
|
|
116
|
+
- 小程序需要将上报域名加入 request 合法域名(开发期可在开发者工具勾选「不校验合法域名」)。
|
|
117
|
+
- 自动可用的采集:设备信息、会话心跳、JS 错误;页面 PV 与自定义事件需手动调用。
|
|
118
|
+
- `console` 全量上报目前依赖运行时劫持;编译期 `transform-console` 插件尚未发布。
|
|
119
|
+
- 上报内容会经过服务端协议校验:单批 ≤50 条、`msg` ≤4000 字符、请求体 ≤512KB,超长由 SDK 自动截断。
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
UNLICENSED(公司内部使用)
|