-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path9.1-strategy-logging.js
88 lines (69 loc) · 1.64 KB
/
9.1-strategy-logging.js
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
import chalk from 'chalk';
import fs from 'fs';
class LogContext {
constructor(logStrategy) {
this.logStrategy = logStrategy;
}
debug(log) {
this.logStrategy.debug(log);
}
warn(log) {
this.logStrategy.warn(log);
}
info(log) {
this.logStrategy.info(log);
}
error(log) {
this.logStrategy.error(log);
}
}
class ConsoleStrategy {
debug(msg) {
const log = `${chalk.cyan('DEBUG')} ${msg}`;
console.debug(log);
}
warn(msg) {
const log = `${chalk.blue('WARN')} ${msg}`;
console.warn(log);
}
info(msg) {
const log = `${chalk.green('INFO')} ${msg}`;
console.info(log);
}
error(msg) {
const log = `${chalk.red('ERROR')} ${msg}`;
console.error(log);
}
}
class FileStrategy {
constructor(filePath) {
this.filePath = filePath;
}
_writeLine(msg) {
fs.appendFileSync(this.filePath, msg);
}
debug(msg) {
this._writeLine(`DEBUG ${msg}\n`);
}
warn(msg) {
this._writeLine(`WARN ${msg}\n`);
}
info(msg) {
this._writeLine(`INFO ${msg}\n`);
}
error(msg) {
this._writeLine(`ERROR ${msg}\n`);
}
}
const consoleStrategy = new ConsoleStrategy();
const fileStrategy = new FileStrategy('logs.txt');
const logFile = new LogContext(fileStrategy);
const logConsole = new LogContext(consoleStrategy);
logFile.error('Cannot read property of undefined');
logFile.warn('Package is deprecated');
logFile.info('DB connected');
logFile.debug(JSON.stringify({ a: 12, b: false }));
logConsole.error('Cannot read property of undefined');
logConsole.warn('Package is deprecated');
logConsole.info('DB connected');
logConsole.debug(JSON.stringify({ a: 12, b: false }));