-
Notifications
You must be signed in to change notification settings - Fork 0
/
sinks.ts
72 lines (64 loc) · 1.78 KB
/
sinks.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
// Copyright 2020 Yamboy1. All rights reserved. MIT license.
import {
yellow,
gray,
red,
bold,
blue,
} from "https://deno.land/[email protected]/fmt/colors.ts";
import { LogEntry, LogLevel, SinkFunction } from "./types.ts";
/** A function that changes the color of a string in the terminal, generally from std/fmt/colors.ts */
export type ColorFunction = (str: string) => string;
/** Options for the console sink */
export interface ConsoleOptions {
/** Whether colors should be enabled*/
enableColors: boolean;
/** Color overrides for the sink */
colorOptions: Partial<ColorOptions>;
}
/** Color overrides for the console sink */
export interface ColorOptions {
debug: ColorFunction;
info: ColorFunction;
warn: ColorFunction;
error: ColorFunction;
critical: ColorFunction;
}
/** A console sink (with colors) */
export function consoleSink({
enableColors = true,
colorOptions: {
debug = gray,
info = blue,
warn = yellow,
error = red,
critical = (str: string) => bold(red(str))
} = {},
}: Partial<ConsoleOptions> = {}): SinkFunction {
return ({ level, formattedMessage }: LogEntry) => {
let color;
if (enableColors) {
color = ({
[LogLevel.DEBUG]: debug,
[LogLevel.INFO]: info,
[LogLevel.WARN]: warn,
[LogLevel.ERROR]: error,
[LogLevel.CRITICAL]: critical,
})[level] ?? ((x: string) => x);
} else {
color = (x: string) => x;
}
console.log(color(formattedMessage));
};
}
/** A basic sink to write to a file */
export function fileSink(filename: string): SinkFunction {
const encoder = new TextEncoder();
return ({ formattedMessage }: LogEntry) => {
Deno.writeFileSync(
filename,
encoder.encode(formattedMessage + "\n"),
{ create: true, append: true },
);
};
}