-
Notifications
You must be signed in to change notification settings - Fork 2
/
9.4-middleware-logging.js
50 lines (39 loc) · 1.23 KB
/
9.4-middleware-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
import chalk from 'chalk';
import fs from 'fs/promises';
// Middleware manager
class LogManager {
constructor() {
this._middlewares = [];
}
use(middleware) {
if (typeof middleware !== 'function') {
throw new Error('Invalid type of middleware. Should be a function');
}
this._middlewares.push(middleware);
}
async log(message) {
let result = message;
for (const middleware of this._middlewares) {
result = await middleware(result);
}
}
}
// Middlewares
const createColorizeMiddleware = ({ color }) => {
if (!chalk[color]) {
throw new Error('Color is unavailable, pick another', color);
}
return message => chalk[color](message);
};
const prependTimestampMiddleware = (message) => `${new Date().toLocaleString()} ${message}`;
const createWriteToFileMiddleware = ({ path }) => async (message) => {
await fs.appendFile(path, message + '\n');
return message;
}
// Usage
const logger = new LogManager();
logger.use(createColorizeMiddleware({ color: 'green' }));
logger.use(prependTimestampMiddleware);
logger.use(createWriteToFileMiddleware({ path: 'logs.txt' }));
logger.use(console.log);
logger.log('Hello World! Hope you get better'); // logs colored message with timestamp, writes to file