-
Notifications
You must be signed in to change notification settings - Fork 208
/
Diagnostics.ts
75 lines (68 loc) · 2.52 KB
/
Diagnostics.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Core
*/
import {
ClientDiagnostics,
ClientDiagnosticsHandler,
DiagnosticsLogEntry,
DiagnosticsLoggerSeverity,
DiagnosticsLogMessage,
DiagnosticsScopeLogs,
} from "@itwin/presentation-common";
/**
* A function which logs messages to the console.
* @beta
*/
export function consoleDiagnosticsHandler(diagnostics: ClientDiagnostics) {
// eslint-disable-next-line no-console
diagnostics.backendVersion && console.log(`Backend version: ${diagnostics.backendVersion}`);
diagnostics.logs &&
handleDiagnosticLogs(diagnostics.logs, (msg: DiagnosticsLogMessage, stack: DiagnosticsScopeLogs[]) => {
/* note: we're duplicating the message if it's logged at both editor and dev severity levels */
const str = buildLogMessageString(msg, stack);
if (msg.severity.editor) {
getConsoleLogFunc(msg.severity.editor)(str);
}
if (msg.severity.dev) {
getConsoleLogFunc(msg.severity.dev)(str);
}
});
}
/**
* A function which calls all diagnostics handlers passed to it.
* @beta
*/
export function createCombinedDiagnosticsHandler(handlers: ClientDiagnosticsHandler[]) {
return (diagnostics: ClientDiagnostics) => {
handlers.forEach((handler) => handler(diagnostics));
};
}
type DiagnosticsLogMessageHandler = (msg: DiagnosticsLogMessage, stack: DiagnosticsScopeLogs[]) => void;
function handleDiagnosticLogs(logs: DiagnosticsLogEntry[], messageHandler: DiagnosticsLogMessageHandler, stack: DiagnosticsScopeLogs[] = []) {
logs.forEach((log) => {
if (DiagnosticsLogEntry.isMessage(log)) {
messageHandler(log, stack);
} else if (log.logs) {
handleDiagnosticLogs(log.logs, messageHandler, [...stack, log]);
}
});
}
function buildLogMessageString(msg: DiagnosticsLogMessage, _stack: DiagnosticsScopeLogs[]) {
return msg.message;
}
function getConsoleLogFunc(severity: DiagnosticsLoggerSeverity) {
switch (severity) {
case "error":
return console.error; // eslint-disable-line no-console
case "warning":
return console.warn; // eslint-disable-line no-console
case "info":
case "debug":
case "trace":
return console.log; // eslint-disable-line no-console
}
}