@logtape/logtape 1.2.2 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/formatter.ts DELETED
@@ -1,961 +0,0 @@
1
- import * as util from "#util";
2
- import type { LogLevel } from "./level.ts";
3
- import type { LogRecord } from "./record.ts";
4
-
5
- /**
6
- * A text formatter is a function that accepts a log record and returns
7
- * a string.
8
- *
9
- * @param record The log record to format.
10
- * @returns The formatted log record.
11
- */
12
- export type TextFormatter = (record: LogRecord) => string;
13
-
14
- /**
15
- * The severity level abbreviations.
16
- */
17
- const levelAbbreviations: Record<LogLevel, string> = {
18
- "trace": "TRC",
19
- "debug": "DBG",
20
- "info": "INF",
21
- "warning": "WRN",
22
- "error": "ERR",
23
- "fatal": "FTL",
24
- };
25
-
26
- /**
27
- * A platform-specific inspect function. In Deno, this is {@link Deno.inspect},
28
- * and in Node.js/Bun it is `util.inspect()`. If neither is available, it
29
- * falls back to {@link JSON.stringify}.
30
- *
31
- * @param value The value to inspect.
32
- * @param options The options for inspecting the value.
33
- * If `colors` is `true`, the output will be ANSI-colored.
34
- * @returns The string representation of the value.
35
- */
36
- const inspect: (value: unknown, options?: { colors?: boolean }) => string =
37
- // @ts-ignore: Browser detection
38
- // dnt-shim-ignore
39
- typeof document !== "undefined" ||
40
- // @ts-ignore: React Native detection
41
- // dnt-shim-ignore
42
- typeof navigator !== "undefined" && navigator.product === "ReactNative"
43
- ? (v) => JSON.stringify(v)
44
- // @ts-ignore: Deno global
45
- // dnt-shim-ignore
46
- : "Deno" in globalThis && "inspect" in globalThis.Deno &&
47
- // @ts-ignore: Deno global
48
- // dnt-shim-ignore
49
- typeof globalThis.Deno.inspect === "function"
50
- ? (v, opts) =>
51
- // @ts-ignore: Deno global
52
- // dnt-shim-ignore
53
- globalThis.Deno.inspect(v, {
54
- strAbbreviateSize: Infinity,
55
- iterableLimit: Infinity,
56
- ...opts,
57
- })
58
- // @ts-ignore: Node.js global
59
- // dnt-shim-ignore
60
- : util != null && "inspect" in util && typeof util.inspect === "function"
61
- ? (v, opts) =>
62
- // @ts-ignore: Node.js global
63
- // dnt-shim-ignore
64
- util.inspect(v, {
65
- maxArrayLength: Infinity,
66
- maxStringLength: Infinity,
67
- ...opts,
68
- })
69
- : (v) => JSON.stringify(v);
70
-
71
- /**
72
- * The formatted values for a log record.
73
- * @since 0.6.0
74
- */
75
- export interface FormattedValues {
76
- /**
77
- * The formatted timestamp.
78
- */
79
- timestamp: string | null;
80
-
81
- /**
82
- * The formatted log level.
83
- */
84
- level: string;
85
-
86
- /**
87
- * The formatted category.
88
- */
89
- category: string;
90
-
91
- /**
92
- * The formatted message.
93
- */
94
- message: string;
95
-
96
- /**
97
- * The unformatted log record.
98
- */
99
- record: LogRecord;
100
- }
101
-
102
- /**
103
- * The various options for the built-in text formatters.
104
- * @since 0.6.0
105
- */
106
- export interface TextFormatterOptions {
107
- /**
108
- * The timestamp format. This can be one of the following:
109
- *
110
- * - `"date-time-timezone"`: The date and time with the full timezone offset
111
- * (e.g., `"2023-11-14 22:13:20.000 +00:00"`).
112
- * - `"date-time-tz"`: The date and time with the short timezone offset
113
- * (e.g., `"2023-11-14 22:13:20.000 +00"`).
114
- * - `"date-time"`: The date and time without the timezone offset
115
- * (e.g., `"2023-11-14 22:13:20.000"`).
116
- * - `"time-timezone"`: The time with the full timezone offset but without
117
- * the date (e.g., `"22:13:20.000 +00:00"`).
118
- * - `"time-tz"`: The time with the short timezone offset but without the date
119
- * (e.g., `"22:13:20.000 +00"`).
120
- * - `"time"`: The time without the date or timezone offset
121
- * (e.g., `"22:13:20.000"`).
122
- * - `"date"`: The date without the time or timezone offset
123
- * (e.g., `"2023-11-14"`).
124
- * - `"rfc3339"`: The date and time in RFC 3339 format
125
- * (e.g., `"2023-11-14T22:13:20.000Z"`).
126
- * - `"none"` or `"disabled"`: No display
127
- *
128
- * Alternatively, this can be a function that accepts a timestamp and returns
129
- * a string.
130
- *
131
- * The default is `"date-time-timezone"`.
132
- */
133
- timestamp?:
134
- | "date-time-timezone"
135
- | "date-time-tz"
136
- | "date-time"
137
- | "time-timezone"
138
- | "time-tz"
139
- | "time"
140
- | "date"
141
- | "rfc3339"
142
- | "none"
143
- | "disabled"
144
- | ((ts: number) => string | null);
145
-
146
- /**
147
- * The log level format. This can be one of the following:
148
- *
149
- * - `"ABBR"`: The log level abbreviation in uppercase (e.g., `"INF"`).
150
- * - `"FULL"`: The full log level name in uppercase (e.g., `"INFO"`).
151
- * - `"L"`: The first letter of the log level in uppercase (e.g., `"I"`).
152
- * - `"abbr"`: The log level abbreviation in lowercase (e.g., `"inf"`).
153
- * - `"full"`: The full log level name in lowercase (e.g., `"info"`).
154
- * - `"l"`: The first letter of the log level in lowercase (e.g., `"i"`).
155
- *
156
- * Alternatively, this can be a function that accepts a log level and returns
157
- * a string.
158
- *
159
- * The default is `"ABBR"`.
160
- */
161
- level?:
162
- | "ABBR"
163
- | "FULL"
164
- | "L"
165
- | "abbr"
166
- | "full"
167
- | "l"
168
- | ((level: LogLevel) => string);
169
-
170
- /**
171
- * The separator between category names. For example, if the separator is
172
- * `"·"`, the category `["a", "b", "c"]` will be formatted as `"a·b·c"`.
173
- * The default separator is `"·"`.
174
- *
175
- * If this is a function, it will be called with the category array and
176
- * should return a string, which will be used for rendering the category.
177
- */
178
- category?: string | ((category: readonly string[]) => string);
179
-
180
- /**
181
- * The format of the embedded values.
182
- *
183
- * A function that renders a value to a string. This function is used to
184
- * render the values in the log record. The default is a cross-runtime
185
- * `inspect()` function that uses [`util.inspect()`] in Node.js/Bun,
186
- * [`Deno.inspect()`] in Deno, or falls back to {@link JSON.stringify} in
187
- * browsers.
188
- *
189
- * The second parameter provides access to the default cross-runtime
190
- * `inspect()` function, allowing you to fall back to the default behavior
191
- * for certain values while customizing others. You can ignore this
192
- * parameter if you don't need the fallback functionality.
193
- *
194
- * [`util.inspect()`]: https://nodejs.org/api/util.html#utilinspectobject-options
195
- * [`Deno.inspect()`]: https://docs.deno.com/api/deno/~/Deno.inspect
196
- * @param value The value to render.
197
- * @param inspect The default cross-runtime inspect function that can be used
198
- * as a fallback. Accepts an optional `options` parameter
199
- * with a `colors` boolean field.
200
- * @returns The string representation of the value.
201
- * @example
202
- * ```typescript
203
- * getTextFormatter({
204
- * value(value, inspect) {
205
- * // Custom formatting for numbers
206
- * if (typeof value === 'number') {
207
- * return value.toFixed(2);
208
- * }
209
- * // Fall back to default for everything else
210
- * return inspect(value);
211
- * }
212
- * })
213
- * ```
214
- */
215
- value?: (
216
- value: unknown,
217
- inspect: (value: unknown, options?: { colors?: boolean }) => string,
218
- ) => string;
219
-
220
- /**
221
- * How those formatted parts are concatenated.
222
- *
223
- * A function that formats the log record. This function is called with the
224
- * formatted values and should return a string. Note that the formatted
225
- * *should not* include a newline character at the end.
226
- *
227
- * By default, this is a function that formats the log record as follows:
228
- *
229
- * ```
230
- * 2023-11-14 22:13:20.000 +00:00 [INF] category·subcategory: Hello, world!
231
- * ```
232
- * @param values The formatted values.
233
- * @returns The formatted log record.
234
- */
235
- format?: (values: FormattedValues) => string;
236
- }
237
-
238
- // Optimized helper functions for timestamp formatting
239
- function padZero(num: number): string {
240
- return num < 10 ? `0${num}` : `${num}`;
241
- }
242
-
243
- function padThree(num: number): string {
244
- return num < 10 ? `00${num}` : num < 100 ? `0${num}` : `${num}`;
245
- }
246
-
247
- // Pre-optimized timestamp formatter functions
248
- const timestampFormatters = {
249
- "date-time-timezone": (ts: number): string => {
250
- const d = new Date(ts);
251
- const year = d.getUTCFullYear();
252
- const month = padZero(d.getUTCMonth() + 1);
253
- const day = padZero(d.getUTCDate());
254
- const hour = padZero(d.getUTCHours());
255
- const minute = padZero(d.getUTCMinutes());
256
- const second = padZero(d.getUTCSeconds());
257
- const ms = padThree(d.getUTCMilliseconds());
258
- return `${year}-${month}-${day} ${hour}:${minute}:${second}.${ms} +00:00`;
259
- },
260
- "date-time-tz": (ts: number): string => {
261
- const d = new Date(ts);
262
- const year = d.getUTCFullYear();
263
- const month = padZero(d.getUTCMonth() + 1);
264
- const day = padZero(d.getUTCDate());
265
- const hour = padZero(d.getUTCHours());
266
- const minute = padZero(d.getUTCMinutes());
267
- const second = padZero(d.getUTCSeconds());
268
- const ms = padThree(d.getUTCMilliseconds());
269
- return `${year}-${month}-${day} ${hour}:${minute}:${second}.${ms} +00`;
270
- },
271
- "date-time": (ts: number): string => {
272
- const d = new Date(ts);
273
- const year = d.getUTCFullYear();
274
- const month = padZero(d.getUTCMonth() + 1);
275
- const day = padZero(d.getUTCDate());
276
- const hour = padZero(d.getUTCHours());
277
- const minute = padZero(d.getUTCMinutes());
278
- const second = padZero(d.getUTCSeconds());
279
- const ms = padThree(d.getUTCMilliseconds());
280
- return `${year}-${month}-${day} ${hour}:${minute}:${second}.${ms}`;
281
- },
282
- "time-timezone": (ts: number): string => {
283
- const d = new Date(ts);
284
- const hour = padZero(d.getUTCHours());
285
- const minute = padZero(d.getUTCMinutes());
286
- const second = padZero(d.getUTCSeconds());
287
- const ms = padThree(d.getUTCMilliseconds());
288
- return `${hour}:${minute}:${second}.${ms} +00:00`;
289
- },
290
- "time-tz": (ts: number): string => {
291
- const d = new Date(ts);
292
- const hour = padZero(d.getUTCHours());
293
- const minute = padZero(d.getUTCMinutes());
294
- const second = padZero(d.getUTCSeconds());
295
- const ms = padThree(d.getUTCMilliseconds());
296
- return `${hour}:${minute}:${second}.${ms} +00`;
297
- },
298
- "time": (ts: number): string => {
299
- const d = new Date(ts);
300
- const hour = padZero(d.getUTCHours());
301
- const minute = padZero(d.getUTCMinutes());
302
- const second = padZero(d.getUTCSeconds());
303
- const ms = padThree(d.getUTCMilliseconds());
304
- return `${hour}:${minute}:${second}.${ms}`;
305
- },
306
- "date": (ts: number): string => {
307
- const d = new Date(ts);
308
- const year = d.getUTCFullYear();
309
- const month = padZero(d.getUTCMonth() + 1);
310
- const day = padZero(d.getUTCDate());
311
- return `${year}-${month}-${day}`;
312
- },
313
- "rfc3339": (ts: number): string => new Date(ts).toISOString(),
314
- "none": (): null => null,
315
- } as const;
316
-
317
- // Pre-computed level renderers for common cases
318
- const levelRenderersCache = {
319
- ABBR: levelAbbreviations,
320
- abbr: {
321
- trace: "trc",
322
- debug: "dbg",
323
- info: "inf",
324
- warning: "wrn",
325
- error: "err",
326
- fatal: "ftl",
327
- } as const,
328
- FULL: {
329
- trace: "TRACE",
330
- debug: "DEBUG",
331
- info: "INFO",
332
- warning: "WARNING",
333
- error: "ERROR",
334
- fatal: "FATAL",
335
- } as const,
336
- full: {
337
- trace: "trace",
338
- debug: "debug",
339
- info: "info",
340
- warning: "warning",
341
- error: "error",
342
- fatal: "fatal",
343
- } as const,
344
- L: {
345
- trace: "T",
346
- debug: "D",
347
- info: "I",
348
- warning: "W",
349
- error: "E",
350
- fatal: "F",
351
- } as const,
352
- l: {
353
- trace: "t",
354
- debug: "d",
355
- info: "i",
356
- warning: "w",
357
- error: "e",
358
- fatal: "f",
359
- } as const,
360
- } as const;
361
-
362
- /**
363
- * Get a text formatter with the specified options. Although it's flexible
364
- * enough to create a custom formatter, if you want more control, you can
365
- * create a custom formatter that satisfies the {@link TextFormatter} type
366
- * instead.
367
- *
368
- * For more information on the options, see {@link TextFormatterOptions}.
369
- *
370
- * By default, the formatter formats log records as follows:
371
- *
372
- * ```
373
- * 2023-11-14 22:13:20.000 +00:00 [INF] category·subcategory: Hello, world!
374
- * ```
375
- * @param options The options for the text formatter.
376
- * @returns The text formatter.
377
- * @since 0.6.0
378
- */
379
- export function getTextFormatter(
380
- options: TextFormatterOptions = {},
381
- ): TextFormatter {
382
- // Pre-compute timestamp formatter with optimized lookup
383
- const timestampRenderer = (() => {
384
- const tsOption = options.timestamp;
385
- if (tsOption == null) {
386
- return timestampFormatters["date-time-timezone"];
387
- } else if (tsOption === "disabled") {
388
- return timestampFormatters["none"];
389
- } else if (
390
- typeof tsOption === "string" && tsOption in timestampFormatters
391
- ) {
392
- return timestampFormatters[tsOption as keyof typeof timestampFormatters];
393
- } else {
394
- return tsOption as (ts: number) => string | null;
395
- }
396
- })();
397
-
398
- const categorySeparator = options.category ?? "·";
399
- const valueRenderer = options.value
400
- ? (v: unknown) => options.value!(v, inspect)
401
- : inspect;
402
-
403
- // Pre-compute level renderer for better performance
404
- const levelRenderer = (() => {
405
- const levelOption = options.level;
406
- if (levelOption == null || levelOption === "ABBR") {
407
- return (level: LogLevel): string => levelRenderersCache.ABBR[level];
408
- } else if (levelOption === "abbr") {
409
- return (level: LogLevel): string => levelRenderersCache.abbr[level];
410
- } else if (levelOption === "FULL") {
411
- return (level: LogLevel): string => levelRenderersCache.FULL[level];
412
- } else if (levelOption === "full") {
413
- return (level: LogLevel): string => levelRenderersCache.full[level];
414
- } else if (levelOption === "L") {
415
- return (level: LogLevel): string => levelRenderersCache.L[level];
416
- } else if (levelOption === "l") {
417
- return (level: LogLevel): string => levelRenderersCache.l[level];
418
- } else {
419
- return levelOption;
420
- }
421
- })();
422
-
423
- const formatter: (values: FormattedValues) => string = options.format ??
424
- (({ timestamp, level, category, message }: FormattedValues) =>
425
- `${timestamp ? `${timestamp} ` : ""}[${level}] ${category}: ${message}`);
426
-
427
- return (record: LogRecord): string => {
428
- // Optimized message building
429
- const msgParts = record.message;
430
- const msgLen = msgParts.length;
431
-
432
- let message: string;
433
- if (msgLen === 1) {
434
- // Fast path for simple messages with no interpolation
435
- message = msgParts[0] as string;
436
- } else if (msgLen <= 6) {
437
- // Fast path for small messages - direct concatenation
438
- message = "";
439
- for (let i = 0; i < msgLen; i++) {
440
- message += (i % 2 === 0) ? msgParts[i] : valueRenderer(msgParts[i]);
441
- }
442
- } else {
443
- // Optimized path for larger messages - array join
444
- const parts: string[] = new Array(msgLen);
445
- for (let i = 0; i < msgLen; i++) {
446
- parts[i] = (i % 2 === 0)
447
- ? msgParts[i] as string
448
- : valueRenderer(msgParts[i]);
449
- }
450
- message = parts.join("");
451
- }
452
-
453
- const timestamp = timestampRenderer(record.timestamp);
454
- const level = levelRenderer(record.level);
455
- const category = typeof categorySeparator === "function"
456
- ? categorySeparator(record.category)
457
- : record.category.join(categorySeparator);
458
-
459
- const values: FormattedValues = {
460
- timestamp,
461
- level,
462
- category,
463
- message,
464
- record,
465
- };
466
- return `${formatter(values)}\n`;
467
- };
468
- }
469
-
470
- /**
471
- * The default text formatter. This formatter formats log records as follows:
472
- *
473
- * ```
474
- * 2023-11-14 22:13:20.000 +00:00 [INF] category·subcategory: Hello, world!
475
- * ```
476
- *
477
- * @param record The log record to format.
478
- * @returns The formatted log record.
479
- */
480
- export const defaultTextFormatter: TextFormatter = getTextFormatter();
481
-
482
- const RESET = "\x1b[0m";
483
-
484
- /**
485
- * The ANSI colors. These can be used to colorize text in the console.
486
- * @since 0.6.0
487
- */
488
- export type AnsiColor =
489
- | "black"
490
- | "red"
491
- | "green"
492
- | "yellow"
493
- | "blue"
494
- | "magenta"
495
- | "cyan"
496
- | "white";
497
-
498
- const ansiColors: Record<AnsiColor, string> = {
499
- black: "\x1b[30m",
500
- red: "\x1b[31m",
501
- green: "\x1b[32m",
502
- yellow: "\x1b[33m",
503
- blue: "\x1b[34m",
504
- magenta: "\x1b[35m",
505
- cyan: "\x1b[36m",
506
- white: "\x1b[37m",
507
- };
508
-
509
- /**
510
- * The ANSI text styles.
511
- * @since 0.6.0
512
- */
513
- export type AnsiStyle =
514
- | "bold"
515
- | "dim"
516
- | "italic"
517
- | "underline"
518
- | "strikethrough";
519
-
520
- const ansiStyles: Record<AnsiStyle, string> = {
521
- bold: "\x1b[1m",
522
- dim: "\x1b[2m",
523
- italic: "\x1b[3m",
524
- underline: "\x1b[4m",
525
- strikethrough: "\x1b[9m",
526
- };
527
-
528
- const defaultLevelColors: Record<LogLevel, AnsiColor | null> = {
529
- trace: null,
530
- debug: "blue",
531
- info: "green",
532
- warning: "yellow",
533
- error: "red",
534
- fatal: "magenta",
535
- };
536
-
537
- /**
538
- * The various options for the ANSI color formatter.
539
- * @since 0.6.0
540
- */
541
- export interface AnsiColorFormatterOptions extends TextFormatterOptions {
542
- /**
543
- * The timestamp format. This can be one of the following:
544
- *
545
- * - `"date-time-timezone"`: The date and time with the full timezone offset
546
- * (e.g., `"2023-11-14 22:13:20.000 +00:00"`).
547
- * - `"date-time-tz"`: The date and time with the short timezone offset
548
- * (e.g., `"2023-11-14 22:13:20.000 +00"`).
549
- * - `"date-time"`: The date and time without the timezone offset
550
- * (e.g., `"2023-11-14 22:13:20.000"`).
551
- * - `"time-timezone"`: The time with the full timezone offset but without
552
- * the date (e.g., `"22:13:20.000 +00:00"`).
553
- * - `"time-tz"`: The time with the short timezone offset but without the date
554
- * (e.g., `"22:13:20.000 +00"`).
555
- * - `"time"`: The time without the date or timezone offset
556
- * (e.g., `"22:13:20.000"`).
557
- * - `"date"`: The date without the time or timezone offset
558
- * (e.g., `"2023-11-14"`).
559
- * - `"rfc3339"`: The date and time in RFC 3339 format
560
- * (e.g., `"2023-11-14T22:13:20.000Z"`).
561
- *
562
- * Alternatively, this can be a function that accepts a timestamp and returns
563
- * a string.
564
- *
565
- * The default is `"date-time-tz"`.
566
- */
567
- timestamp?:
568
- | "date-time-timezone"
569
- | "date-time-tz"
570
- | "date-time"
571
- | "time-timezone"
572
- | "time-tz"
573
- | "time"
574
- | "date"
575
- | "rfc3339"
576
- | ((ts: number) => string);
577
-
578
- /**
579
- * The ANSI style for the timestamp. `"dim"` is used by default.
580
- */
581
- timestampStyle?: AnsiStyle | null;
582
-
583
- /**
584
- * The ANSI color for the timestamp. No color is used by default.
585
- */
586
- timestampColor?: AnsiColor | null;
587
-
588
- /**
589
- * The ANSI style for the log level. `"bold"` is used by default.
590
- */
591
- levelStyle?: AnsiStyle | null;
592
-
593
- /**
594
- * The ANSI colors for the log levels. The default colors are as follows:
595
- *
596
- * - `"trace"`: `null` (no color)
597
- * - `"debug"`: `"blue"`
598
- * - `"info"`: `"green"`
599
- * - `"warning"`: `"yellow"`
600
- * - `"error"`: `"red"`
601
- * - `"fatal"`: `"magenta"`
602
- */
603
- levelColors?: Record<LogLevel, AnsiColor | null>;
604
-
605
- /**
606
- * The ANSI style for the category. `"dim"` is used by default.
607
- */
608
- categoryStyle?: AnsiStyle | null;
609
-
610
- /**
611
- * The ANSI color for the category. No color is used by default.
612
- */
613
- categoryColor?: AnsiColor | null;
614
- }
615
-
616
- /**
617
- * Get an ANSI color formatter with the specified options.
618
- *
619
- * ![A preview of an ANSI color formatter.](https://i.imgur.com/I8LlBUf.png)
620
- * @param option The options for the ANSI color formatter.
621
- * @returns The ANSI color formatter.
622
- * @since 0.6.0
623
- */
624
- export function getAnsiColorFormatter(
625
- options: AnsiColorFormatterOptions = {},
626
- ): TextFormatter {
627
- const format = options.format;
628
- const timestampStyle = typeof options.timestampStyle === "undefined"
629
- ? "dim"
630
- : options.timestampStyle;
631
- const timestampColor = options.timestampColor ?? null;
632
- const timestampPrefix = `${
633
- timestampStyle == null ? "" : ansiStyles[timestampStyle]
634
- }${timestampColor == null ? "" : ansiColors[timestampColor]}`;
635
- const timestampSuffix = timestampStyle == null && timestampColor == null
636
- ? ""
637
- : RESET;
638
- const levelStyle = typeof options.levelStyle === "undefined"
639
- ? "bold"
640
- : options.levelStyle;
641
- const levelColors = options.levelColors ?? defaultLevelColors;
642
- const categoryStyle = typeof options.categoryStyle === "undefined"
643
- ? "dim"
644
- : options.categoryStyle;
645
- const categoryColor = options.categoryColor ?? null;
646
- const categoryPrefix = `${
647
- categoryStyle == null ? "" : ansiStyles[categoryStyle]
648
- }${categoryColor == null ? "" : ansiColors[categoryColor]}`;
649
- const categorySuffix = categoryStyle == null && categoryColor == null
650
- ? ""
651
- : RESET;
652
- return getTextFormatter({
653
- timestamp: "date-time-tz",
654
- value(value: unknown, fallbackInspect): string {
655
- return fallbackInspect(value, { colors: true });
656
- },
657
- ...options,
658
- format({ timestamp, level, category, message, record }): string {
659
- const levelColor = levelColors[record.level];
660
- timestamp = `${timestampPrefix}${timestamp}${timestampSuffix}`;
661
- level = `${levelStyle == null ? "" : ansiStyles[levelStyle]}${
662
- levelColor == null ? "" : ansiColors[levelColor]
663
- }${level}${levelStyle == null && levelColor == null ? "" : RESET}`;
664
- return format == null
665
- ? `${timestamp} ${level} ${categoryPrefix}${category}:${categorySuffix} ${message}`
666
- : format({
667
- timestamp,
668
- level,
669
- category: `${categoryPrefix}${category}${categorySuffix}`,
670
- message,
671
- record,
672
- });
673
- },
674
- });
675
- }
676
-
677
- /**
678
- * A text formatter that uses ANSI colors to format log records.
679
- *
680
- * ![A preview of ansiColorFormatter.](https://i.imgur.com/I8LlBUf.png)
681
- *
682
- * @param record The log record to format.
683
- * @returns The formatted log record.
684
- * @since 0.5.0
685
- */
686
- export const ansiColorFormatter: TextFormatter = getAnsiColorFormatter();
687
-
688
- /**
689
- * Options for the {@link getJsonLinesFormatter} function.
690
- * @since 0.11.0
691
- */
692
- export interface JsonLinesFormatterOptions {
693
- /**
694
- * The separator between category names. For example, if the separator is
695
- * `"."`, the category `["a", "b", "c"]` will be formatted as `"a.b.c"`.
696
- * If this is a function, it will be called with the category array and
697
- * should return a string or an array of strings, which will be used
698
- * for rendering the category.
699
- *
700
- * @default `"."`
701
- */
702
- readonly categorySeparator?:
703
- | string
704
- | ((category: readonly string[]) => string | readonly string[]);
705
-
706
- /**
707
- * The message format. This can be one of the following:
708
- *
709
- * - `"template"`: The raw message template is used as the message.
710
- * - `"rendered"`: The message is rendered with the values.
711
- *
712
- * @default `"rendered"`
713
- */
714
- readonly message?: "template" | "rendered";
715
-
716
- /**
717
- * The properties format. This can be one of the following:
718
- *
719
- * - `"flatten"`: The properties are flattened into the root object.
720
- * - `"prepend:<prefix>"`: The properties are prepended with the given prefix
721
- * (e.g., `"prepend:ctx_"` will prepend `ctx_` to each property key).
722
- * - `"nest:<key>"`: The properties are nested under the given key
723
- * (e.g., `"nest:properties"` will nest the properties under the
724
- * `properties` key).
725
- *
726
- * @default `"nest:properties"`
727
- */
728
- readonly properties?: "flatten" | `prepend:${string}` | `nest:${string}`;
729
- }
730
-
731
- /**
732
- * Get a [JSON Lines] formatter with the specified options. The log records
733
- * will be rendered as JSON objects, one per line, which is a common format
734
- * for log files. This format is also known as Newline-Delimited JSON (NDJSON).
735
- * It looks like this:
736
- *
737
- * ```json
738
- * {"@timestamp":"2023-11-14T22:13:20.000Z","level":"INFO","message":"Hello, world!","logger":"my.logger","properties":{"key":"value"}}
739
- * ```
740
- *
741
- * [JSON Lines]: https://jsonlines.org/
742
- * @param options The options for the JSON Lines formatter.
743
- * @returns The JSON Lines formatter.
744
- * @since 0.11.0
745
- */
746
- export function getJsonLinesFormatter(
747
- options: JsonLinesFormatterOptions = {},
748
- ): TextFormatter {
749
- // Most common configuration - optimize for the default case
750
- if (!options.categorySeparator && !options.message && !options.properties) {
751
- // Ultra-minimalist path - eliminate all possible overhead
752
- return (record: LogRecord): string => {
753
- // Direct benchmark pattern match (most common case first)
754
- if (record.message.length === 3) {
755
- return JSON.stringify({
756
- "@timestamp": new Date(record.timestamp).toISOString(),
757
- level: record.level === "warning"
758
- ? "WARN"
759
- : record.level.toUpperCase(),
760
- message: record.message[0] + JSON.stringify(record.message[1]) +
761
- record.message[2],
762
- logger: record.category.join("."),
763
- properties: record.properties,
764
- }) + "\n";
765
- }
766
-
767
- // Single message (second most common)
768
- if (record.message.length === 1) {
769
- return JSON.stringify({
770
- "@timestamp": new Date(record.timestamp).toISOString(),
771
- level: record.level === "warning"
772
- ? "WARN"
773
- : record.level.toUpperCase(),
774
- message: record.message[0],
775
- logger: record.category.join("."),
776
- properties: record.properties,
777
- }) + "\n";
778
- }
779
-
780
- // Complex messages (fallback)
781
- let msg = record.message[0] as string;
782
- for (let i = 1; i < record.message.length; i++) {
783
- msg += (i & 1) ? JSON.stringify(record.message[i]) : record.message[i];
784
- }
785
-
786
- return JSON.stringify({
787
- "@timestamp": new Date(record.timestamp).toISOString(),
788
- level: record.level === "warning" ? "WARN" : record.level.toUpperCase(),
789
- message: msg,
790
- logger: record.category.join("."),
791
- properties: record.properties,
792
- }) + "\n";
793
- };
794
- }
795
-
796
- // Pre-compile configuration for non-default cases
797
- const isTemplateMessage = options.message === "template";
798
- const propertiesOption = options.properties ?? "nest:properties";
799
-
800
- // Pre-compile category joining strategy
801
- let joinCategory: (category: readonly string[]) => string | readonly string[];
802
- if (typeof options.categorySeparator === "function") {
803
- joinCategory = options.categorySeparator;
804
- } else {
805
- const separator = options.categorySeparator ?? ".";
806
- joinCategory = (category: readonly string[]): string =>
807
- category.join(separator);
808
- }
809
-
810
- // Pre-compile properties handling strategy
811
- let getProperties: (
812
- properties: Record<string, unknown>,
813
- ) => Record<string, unknown>;
814
-
815
- if (propertiesOption === "flatten") {
816
- getProperties = (properties) => properties;
817
- } else if (propertiesOption.startsWith("prepend:")) {
818
- const prefix = propertiesOption.substring(8);
819
- if (prefix === "") {
820
- throw new TypeError(
821
- `Invalid properties option: ${
822
- JSON.stringify(propertiesOption)
823
- }. It must be of the form "prepend:<prefix>" where <prefix> is a non-empty string.`,
824
- );
825
- }
826
- getProperties = (properties) => {
827
- const result: Record<string, unknown> = {};
828
- for (const key in properties) {
829
- result[`${prefix}${key}`] = properties[key];
830
- }
831
- return result;
832
- };
833
- } else if (propertiesOption.startsWith("nest:")) {
834
- const key = propertiesOption.substring(5);
835
- getProperties = (properties) => ({ [key]: properties });
836
- } else {
837
- throw new TypeError(
838
- `Invalid properties option: ${
839
- JSON.stringify(propertiesOption)
840
- }. It must be "flatten", "prepend:<prefix>", or "nest:<key>".`,
841
- );
842
- }
843
-
844
- // Pre-compile message rendering function
845
- let getMessage: (record: LogRecord) => string;
846
-
847
- if (isTemplateMessage) {
848
- getMessage = (record: LogRecord): string => {
849
- if (typeof record.rawMessage === "string") {
850
- return record.rawMessage;
851
- }
852
- let msg = "";
853
- for (let i = 0; i < record.rawMessage.length; i++) {
854
- msg += i % 2 < 1 ? record.rawMessage[i] : "{}";
855
- }
856
- return msg;
857
- };
858
- } else {
859
- getMessage = (record: LogRecord): string => {
860
- const msgLen = record.message.length;
861
-
862
- if (msgLen === 1) {
863
- return record.message[0] as string;
864
- }
865
-
866
- let msg = "";
867
- for (let i = 0; i < msgLen; i++) {
868
- msg += (i % 2 < 1)
869
- ? record.message[i]
870
- : JSON.stringify(record.message[i]);
871
- }
872
- return msg;
873
- };
874
- }
875
-
876
- return (record: LogRecord): string => {
877
- return JSON.stringify({
878
- "@timestamp": new Date(record.timestamp).toISOString(),
879
- level: record.level === "warning" ? "WARN" : record.level.toUpperCase(),
880
- message: getMessage(record),
881
- logger: joinCategory(record.category),
882
- ...getProperties(record.properties),
883
- }) + "\n";
884
- };
885
- }
886
-
887
- /**
888
- * The default [JSON Lines] formatter. This formatter formats log records
889
- * as JSON objects, one per line, which is a common format for log files.
890
- * It looks like this:
891
- *
892
- * ```json
893
- * {"@timestamp":"2023-11-14T22:13:20.000Z","level":"INFO","message":"Hello, world!","logger":"my.logger","properties":{"key":"value"}}
894
- * ```
895
- *
896
- * You can customize the output by passing options to
897
- * {@link getJsonLinesFormatter}. For example, you can change the category
898
- * separator, the message format, and how the properties are formatted.
899
- *
900
- * [JSON Lines]: https://jsonlines.org/
901
- * @since 0.11.0
902
- */
903
- export const jsonLinesFormatter: TextFormatter = getJsonLinesFormatter();
904
-
905
- /**
906
- * A console formatter is a function that accepts a log record and returns
907
- * an array of arguments to pass to {@link console.log}.
908
- *
909
- * @param record The log record to format.
910
- * @returns The formatted log record, as an array of arguments for
911
- * {@link console.log}.
912
- */
913
- export type ConsoleFormatter = (record: LogRecord) => readonly unknown[];
914
-
915
- /**
916
- * The styles for the log level in the console.
917
- */
918
- const logLevelStyles: Record<LogLevel, string> = {
919
- "trace": "background-color: gray; color: white;",
920
- "debug": "background-color: gray; color: white;",
921
- "info": "background-color: white; color: black;",
922
- "warning": "background-color: orange; color: black;",
923
- "error": "background-color: red; color: white;",
924
- "fatal": "background-color: maroon; color: white;",
925
- };
926
-
927
- /**
928
- * The default console formatter.
929
- *
930
- * @param record The log record to format.
931
- * @returns The formatted log record, as an array of arguments for
932
- * {@link console.log}.
933
- */
934
- export function defaultConsoleFormatter(record: LogRecord): readonly unknown[] {
935
- let msg = "";
936
- const values: unknown[] = [];
937
- for (let i = 0; i < record.message.length; i++) {
938
- if (i % 2 === 0) msg += record.message[i];
939
- else {
940
- msg += "%o";
941
- values.push(record.message[i]);
942
- }
943
- }
944
- const date = new Date(record.timestamp);
945
- const time = `${date.getUTCHours().toString().padStart(2, "0")}:${
946
- date.getUTCMinutes().toString().padStart(2, "0")
947
- }:${date.getUTCSeconds().toString().padStart(2, "0")}.${
948
- date.getUTCMilliseconds().toString().padStart(3, "0")
949
- }`;
950
- return [
951
- `%c${time} %c${levelAbbreviations[record.level]}%c %c${
952
- record.category.join("\xb7")
953
- } %c${msg}`,
954
- "color: gray;",
955
- logLevelStyles[record.level],
956
- "background-color: default;",
957
- "color: gray;",
958
- "color: default;",
959
- ...values,
960
- ];
961
- }