-
Notifications
You must be signed in to change notification settings - Fork 0
/
log-writer.ts
261 lines (227 loc) · 6.7 KB
/
log-writer.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import { ZLogDetails } from '../messages/log-details.js';
import { ZLogMessage } from '../messages/log-message.js';
import { ZLogField } from './log-field.js';
/**
* Log message writer.
*
* The {@link ZLogField log fields} format and write log message contents using this writer.
*
* The instance of this class can be reused by different messages and fields.
*/
export abstract class ZLogWriter {
/**
* The log message to format and write.
*/
abstract readonly message: ZLogMessage;
/**
* Changes the message to write.
*
* A field may decide to modify the message e.g. to exclude some of its properties from further formatting.
*
* @param newMessage - New message to format.
*/
abstract changeMessage(newMessage: ZLogMessage): void;
/**
* Extracts {@link ZLogMessage.details message details}, then {@link changeMessage changes} the message to write
* by excluding the extracted details from it.
*
* @returns Extracted message details.
*/
extractDetail(): ZLogDetails;
/**
* Extracts a property from {@link ZLogMessage.details message details}, then {@link changeMessage changes}
* the message to write by excluding the extracted property from it.
*
* @param path - A path to details property to extract. Empty path means extracting of all details.
*
* @returns Extracted message detail, or `undefined` if there is no such detail.
*/
extractDetail(...path: (keyof ZLogDetails)[]): unknown;
extractDetail(...path: (keyof ZLogDetails)[]): unknown {
const { message } = this;
const last = path.length - 1;
let { details } = message;
if (last < 0) {
// Empty path - extracting all details.
this.changeMessage({ ...message, details: {} });
return details;
}
let detailsReplacement!: Record<keyof ZLogDetails, unknown>;
let updatedDetails: Record<keyof ZLogDetails, unknown> = {};
for (let i = 0; ; ++i) {
const key = path[i] as string;
const value = details[key];
if (value === undefined) {
return;
}
if (!i) {
detailsReplacement = updatedDetails = { ...details };
}
if (i === last) {
delete updatedDetails[key];
ZLogLine$compactDetails(detailsReplacement, path, 0);
this.changeMessage({ ...message, details: detailsReplacement });
return value;
}
if (value == null || typeof value !== 'object') {
return; // No such detail.
}
updatedDetails = updatedDetails[key] = { ...value };
details = value as ZLogDetails;
}
}
/**
* Formats a log message by the given field.
*
* @param field - The field to format the message by.
* @param message - The message to format. {@link message Current message} by default.
*
* @returns Either a formatted field string, or `undefined` if nothing to format.
*/
abstract format(field: ZLogField<this>, message?: ZLogMessage): string | undefined;
/**
* Writes raw string.
*
* @param value - Raw string to write.
*/
abstract write(value: string): void;
/**
* Writes arbitrary value.
*
* @param value - A value to write.
*/
writeValue(value: unknown): void {
if (typeof value === 'string') {
this.writeString(value);
} else if (value != null && typeof value === 'object') {
this.writeObject(value);
} else {
this.writeByDefault(value);
}
}
/**
* Writes an error.
*
* Writes a message and its stack trace if present.
*
* @param error - An error to write.
*/
writeError(error: unknown): void {
if (error instanceof Error) {
const { stack } = error;
this.write(stack ? String(stack) : String(error));
} else {
this.write('[Error: ');
this.writeValue(error);
this.write(']');
}
}
/**
* Writes formatted string.
*
* Encloses the string in double quotes.
*
* @param value - A string to write.
*/
writeString(value: string): void {
this.write(JSON.stringify(value));
}
/**
* Writes arbitrary object value.
*
* For array, writes its elements by {@link writeElements}, and encloses them into square brackets.
*
* For anything else, writes object properties by {@link writeProperties}, and encloses them into curly brackets.
*
* @param value - Object value to write.
*/
writeObject(value: object): void {
if (Array.isArray(value)) {
this.write('[');
this.writeElements(value);
this.write(']');
} else {
const formatted = this.format(writer => writer.writeProperties(value));
this.write(formatted ? `{ ${formatted} }` : '{}');
}
}
/**
* Writes object properties.
*
* Writes own object properties by {@link writeKeyAndValue}.
*
* @param value - Object value to write.
*/
writeProperties(value: object): void;
writeProperties(value: Record<PropertyKey, any>): void {
let written = false;
for (const key of Reflect.ownKeys(value)) {
const formatted = this.format(writer => writer.writeKeyAndValue(key, value[key]));
if (formatted != null) {
if (written) {
this.write(', ');
} else {
written = true;
}
this.write(formatted);
}
}
}
/**
* Writes elements of arbitrary iterable.
*
* Writes each element by {@link writeValue}, and separates them with comma.
*
* @param value - An iterable of elements to write.
*/
writeElements(value: Iterable<any>): void {
let written = false;
for (const param of value) {
if (written) {
this.write(', ');
} else {
written = true;
}
this.writeValue(param);
}
}
/**
* Writes arbitrary key/value pair.
*
* Ignores properties with undefined values.
*
* Writes value by {@link writeValue} method. Separates key and value by colon.
*
* @param key - Property key to write.
* @param value - Property value to write.
*/
writeKeyAndValue(key: PropertyKey, value: unknown): void {
if (value !== undefined) {
this.write(`${String(key)}: `);
this.writeValue(value);
}
}
/**
* Writes a value not recognized by {@link writeValue}.
*
* Writes a string representation of the value.
*
* @param value - A value to format.
*/
protected writeByDefault(value: unknown): void {
this.write(String(value));
}
}
function ZLogLine$compactDetails(
details: Record<keyof ZLogDetails, any>,
path: (keyof ZLogDetails)[],
index: number,
): boolean {
const key = path[index] as string;
const nested = details[key];
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
if (nested && ZLogLine$compactDetails(nested, path, index + 1)) {
delete details[key];
}
return !Reflect.ownKeys(details).length;
}