-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlogger.ts
90 lines (71 loc) · 2.41 KB
/
logger.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
/* eslint-disable @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-empty-function, no-restricted-syntax */
declare const Zotero: any
declare const dump: (msg: string) => void
function stringifyXPCOM(obj): string {
if (!obj.QueryInterface) return ''
if (obj.message) return `[XPCOM error ${obj.message}]`
if (obj.name) return `[XPCOM object ${obj.name}]`
return '[XPCOM object]'
}
function stringifyError(obj) {
if (obj instanceof Error) return `[error: ${obj.message || '<unspecified error>'}\n${obj.stack}]`
// guess it is an errorevent
if (obj.error instanceof Error && obj.message) return `[errorevent: ${obj.message} ${stringifyError(obj.error)}]`
if (typeof ErrorEvent !== 'undefined' && obj instanceof ErrorEvent) return `[errorevent: ${obj.message || '<unspecified errorevent>'}]`
return ''
}
function replacer() {
const seen = new WeakSet()
return (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) return '[Circular]'
seen.add(value)
}
if (value === null) return value
if (value instanceof Set) return [...value]
if (value instanceof Map) return Object.fromEntries(value)
switch (typeof value) {
case 'string':
case 'number':
case 'boolean':
return value
case 'object':
return stringifyXPCOM(value) || stringifyError(value) || value
}
if (Array.isArray(value)) return value
return undefined
}
}
export class Logger {
public phase = ''
public indent?: number
constructor(public id: string) {
}
#prefix(error?: any) {
return `{${error ? 'error: ' : ''}${this.phase}${this.id}} `
}
public debug(...msg): void {
Zotero.debug(`${this.#prefix()}${this.format(...msg)}\n`)
}
public info(...msg): void {
Zotero.debug(`${this.#prefix()}${this.format(...msg)}\n`)
}
public error(...msg): void {
Zotero.debug(`${this.#prefix(true)}${this.format(...msg)}\n`)
}
public dump(msg: string, error?: Error): void {
if (error) {
dump(`${this.#prefix(error)}${this.format(msg, error)}\n`)
}
else {
dump(`${this.#prefix()}${this.format(msg)}\n`)
}
}
private to_s(obj: any): string {
if (typeof obj === 'string') return obj
return JSON.stringify(obj, replacer(), this.indent)
}
public format(...msg): string {
return msg.map(m => this.to_s(m)).join(' ')
}
}