diff options
author | Paul Frazee <pfrazee@gmail.com> | 2023-01-02 17:38:13 -0600 |
---|---|---|
committer | Paul Frazee <pfrazee@gmail.com> | 2023-01-02 17:38:13 -0600 |
commit | f6a0e634d78eb97d1d877033bf620ea982038731 (patch) | |
tree | 5d6b7ccbc8f6a587c3910c760bceeefda0c0a291 /src/state/models/log.ts | |
parent | 99cec71ed798b29079eb474acd6f7cc799b51a51 (diff) | |
download | voidsky-f6a0e634d78eb97d1d877033bf620ea982038731.tar.zst |
Implement logging system
Diffstat (limited to 'src/state/models/log.ts')
-rw-r--r-- | src/state/models/log.ts | 94 |
1 files changed, 94 insertions, 0 deletions
diff --git a/src/state/models/log.ts b/src/state/models/log.ts new file mode 100644 index 000000000..42172a3b1 --- /dev/null +++ b/src/state/models/log.ts @@ -0,0 +1,94 @@ +import {makeAutoObservable} from 'mobx' +import {isObj, hasProp} from '../lib/type-guards' + +interface LogEntry { + id: string + type?: string + summary?: string + details?: string + ts?: number +} + +let _lastTs: string +let _lastId: string +function genId(): string { + let candidate = String(Date.now()) + if (_lastTs === candidate) { + const id = _lastId + 'x' + _lastId = id + return id + } + _lastTs = candidate + _lastId = candidate + return candidate +} + +export class LogModel { + entries: LogEntry[] = [] + + constructor() { + makeAutoObservable(this, {serialize: false, hydrate: false}) + } + + serialize(): unknown { + return { + entries: this.entries.slice(-100), + } + } + + hydrate(v: unknown) { + if (isObj(v)) { + if (hasProp(v, 'entries') && Array.isArray(v.entries)) { + this.entries = v.entries.filter( + e => isObj(e) && hasProp(e, 'id') && typeof e.id === 'string', + ) + } + } + } + + private add(entry: LogEntry) { + this.entries.push(entry) + } + + debug(summary: string, details?: any) { + if (details && typeof details !== 'string') { + details = JSON.stringify(details, null, 2) + } + console.debug(summary, details || '') + this.add({ + id: genId(), + type: 'debug', + summary, + details, + ts: Date.now(), + }) + } + + warn(summary: string, details?: any) { + if (details && typeof details !== 'string') { + details = JSON.stringify(details, null, 2) + } + console.warn(summary, details || '') + this.add({ + id: genId(), + type: 'warn', + summary, + details, + ts: Date.now(), + }) + } + + error(summary: string, details?: any) { + if (details && typeof details !== 'string') { + details = JSON.stringify(details, null, 2) + } + console.error(summary, details || '') + this.add({ + id: genId(), + type: 'error', + summary, + details, + ts: Date.now(), + }) + } +} |