-
Notifications
You must be signed in to change notification settings - Fork 213
/
index.ts
243 lines (225 loc) · 5.01 KB
/
index.ts
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
import { invoke } from "@tauri-apps/api/core";
import { listen, type UnlistenFn, type Event } from "@tauri-apps/api/event";
export interface LogOptions {
file?: string;
line?: number;
keyValues?: Record<string, string | undefined>;
}
enum LogLevel {
/**
* The "trace" level.
*
* Designates very low priority, often extremely verbose, information.
*/
Trace = 1,
/**
* The "debug" level.
*
* Designates lower priority information.
*/
Debug,
/**
* The "info" level.
*
* Designates useful information.
*/
Info,
/**
* The "warn" level.
*
* Designates hazardous situations.
*/
Warn,
/**
* The "error" level.
*
* Designates very serious errors.
*/
Error,
}
async function log(
level: LogLevel,
message: string,
options?: LogOptions,
): Promise<void> {
const traces = new Error().stack?.split("\n").map((line) => line.split("@"));
const filtered = traces?.filter(([name, location]) => {
return name.length > 0 && location !== "[native code]";
});
const { file, line, keyValues } = options ?? {};
let location = filtered?.[0]?.filter((v) => v.length > 0).join("@");
if (location === "Error") {
location = "webview::unknown";
}
await invoke("plugin:log|log", {
level,
message,
location,
file,
line,
keyValues,
});
}
/**
* Logs a message at the error level.
*
* @param message
*
* # Examples
*
* ```js
* import { error } from '@tauri-apps/plugin-log';
*
* const err_info = "No connection";
* const port = 22;
*
* error(`Error: ${err_info} on port ${port}`);
* ```
*/
export async function error(
message: string,
options?: LogOptions,
): Promise<void> {
await log(LogLevel.Error, message, options);
}
/**
* Logs a message at the warn level.
*
* @param message
*
* # Examples
*
* ```js
* import { warn } from '@tauri-apps/plugin-log';
*
* const warn_description = "Invalid Input";
*
* warn(`Warning! {warn_description}!`);
* ```
*/
export async function warn(
message: string,
options?: LogOptions,
): Promise<void> {
await log(LogLevel.Warn, message, options);
}
/**
* Logs a message at the info level.
*
* @param message
*
* # Examples
*
* ```js
* import { info } from '@tauri-apps/plugin-log';
*
* const conn_info = { port: 40, speed: 3.20 };
*
* info(`Connected to port {conn_info.port} at {conn_info.speed} Mb/s`);
* ```
*/
export async function info(
message: string,
options?: LogOptions,
): Promise<void> {
await log(LogLevel.Info, message, options);
}
/**
* Logs a message at the debug level.
*
* @param message
*
* # Examples
*
* ```js
* import { debug } from '@tauri-apps/plugin-log';
*
* const pos = { x: 3.234, y: -1.223 };
*
* debug(`New position: x: {pos.x}, y: {pos.y}`);
* ```
*/
export async function debug(
message: string,
options?: LogOptions,
): Promise<void> {
await log(LogLevel.Debug, message, options);
}
/**
* Logs a message at the trace level.
*
* @param message
*
* # Examples
*
* ```js
* import { trace } from '@tauri-apps/plugin-log';
*
* let pos = { x: 3.234, y: -1.223 };
*
* trace(`Position is: x: {pos.x}, y: {pos.y}`);
* ```
*/
export async function trace(
message: string,
options?: LogOptions,
): Promise<void> {
await log(LogLevel.Trace, message, options);
}
interface RecordPayload {
level: LogLevel;
message: string;
}
type LoggerFn = (fn: RecordPayload) => void;
/**
* Attaches a listener for the log, and calls the passed function for each log entry.
* @param fn
*
* @returns a function to cancel the listener.
*/
export async function attachLogger(fn: LoggerFn): Promise<UnlistenFn> {
return await listen("log://log", (event: Event<RecordPayload>) => {
const { level } = event.payload;
let { message } = event.payload;
// Strip ANSI escape codes
message = message.replace(
// TODO: Investigate security/detect-unsafe-regex
// eslint-disable-next-line no-control-regex, security/detect-unsafe-regex
/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
"",
);
fn({ message, level });
});
}
/**
* Attaches a listener that writes log entries to the console as they come in.
*
* @returns a function to cancel the listener.
*/
export async function attachConsole(): Promise<UnlistenFn> {
return await attachLogger(({ level, message }: RecordPayload) => {
switch (level) {
case LogLevel.Trace:
console.log(message);
break;
case LogLevel.Debug:
console.debug(message);
break;
case LogLevel.Info:
console.info(message);
break;
case LogLevel.Warn:
console.warn(message);
break;
case LogLevel.Error:
console.error(message);
break;
default:
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new Error(`unknown log level ${level}`);
}
});
}