/
Transport.ts
49 lines (39 loc) 路 1.25 KB
/
Transport.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
import os from 'node:os';
import { Contract } from '@boost/common';
import type { Blueprint, Schemas } from '@boost/common/optimal';
import { LOG_LEVELS } from './constants';
import * as formats from './formats';
import type { Formatter, LogItem, LogLevel, Transportable, TransportOptions } from './types';
export abstract class Transport<Options extends TransportOptions>
extends Contract<Options>
implements Transportable
{
readonly levels: LogLevel[] = [];
constructor(options: Options) {
super(options);
this.levels = this.options.levels;
}
blueprint(schemas: Schemas): Blueprint<TransportOptions> {
const { array, func, string } = schemas;
return {
eol: string(os.EOL),
format: func<Formatter>(),
levels: array().of(string().oneOf(LOG_LEVELS)),
};
}
/**
* Format the log item into a message string, and append a trailing newline if missing.
*/
format(item: LogItem): string {
const { eol, format } = this.options;
let output = typeof format === 'function' ? format(item) : formats.debug(item);
if (eol && !output.endsWith(eol)) {
output += String(eol);
}
return output;
}
/**
* Write the formatted message according to the transport.
*/
abstract write(message: string, item: LogItem): Promise<void> | void;
}