-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApplicationLogger.js
More file actions
163 lines (148 loc) · 5.77 KB
/
ApplicationLogger.js
File metadata and controls
163 lines (148 loc) · 5.77 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import { createLogger, format, transports } from 'winston';
import dayjs from 'dayjs';
import timezone from 'dayjs/plugin/timezone.js';
import utc from 'dayjs/plugin/utc.js';
import os from 'os';
import { threadId, isMainThread } from 'worker_threads';
import cluster from 'node:cluster';
import colors from 'colors/safe.js';
dayjs.extend(utc);
dayjs.extend(timezone);
const { combine, printf } = format;
/**
* ApplicationLogger class for structured and formatted logging.
*/
class ApplicationLogger {
/**
* Constructor for ApplicationLogger.
* @param {string} service - The name of the service or microservice.
* @param {string} [app=''] - The specific part of the service generating the log.
* @param {string} [timezone=Intl.DateTimeFormat().resolvedOptions().timeZone] - The timezone for formatting timestamps.
* @param {Object} [blocks={}] - Initial blocks for the logger instance.
*/
constructor(service, app = '', timezone = Intl.DateTimeFormat().resolvedOptions().timeZone, blocks = {}) {
this.service = service;
this.app = app;
this.timezone = timezone;
this.blocks = { ...blocks };
this.hostname = process.env.HOSTNAME || os.hostname();
// Create a Winston logger instance with the specified format and transports
this.logger = createLogger({
level: 'info',
format: combine(
printf(({ level, message }) => {
let workerType = 'Worker'
let workerId = String(process.pid)
if (cluster.isPrimary && isMainThread) {
workerType = 'Master'
// workerId = `0`
}
else {
workerId = String(process.pid)
if (!isMainThread) {
workerType = 'Thread'
workerId = process.pid + `/` + threadId
}
}
const worker = colors.gray(`${workerType} ${String(workerId).padStart(5, ' ')}`);
const formattedTimestamp = colors.gray(dayjs().tz(this.timezone).format('YYYY-MM-DD HH:mm:ss'));
const hostname = colors.gray(this.hostname);
const service = colors.white(this.service);
const app = colors.cyan(this.app);
const levelColor = level.toUpperCase() === 'INFO' ? colors.green : level.toUpperCase() === 'ERROR' ? colors.red : colors.yellow;
const coloredLevel = levelColor(level.toUpperCase());
const blocksString = Object.entries(this.blocks)
.map(([key, { value, color }]) => {
const coloredValue = value ? (color ? colors[color](value) : colors.green(value)) : '';
return `[${key}${coloredValue ? `=${coloredValue}` : ''}]`;
})
.join('');
return `[${formattedTimestamp}][${worker}][${coloredLevel}][${service}][${app}]${blocksString} ${message}`;
})
),
transports: [
new transports.Console()
],
});
// Add color methods to the class
this.addColorMethods();
}
/**
* Add color methods to the class.
*/
addColorMethods() {
this.black = (text) => colors.black(text);
this.red = (text) => colors.red(text);
this.green = (text) => colors.green(text);
this.yellow = (text) => colors.yellow(text);
this.blue = (text) => colors.blue(text);
this.magenta = (text) => colors.magenta(text);
this.cyan = (text) => colors.cyan(text);
this.white = (text) => colors.white(text);
this.gray = (text) => colors.gray(text);
this.grey = (text) => colors.grey(text);
}
/**
* Create a new logger instance for a specific app and optionally a different timezone.
* @param {string} app - The specific part of the service generating the log.
* @param {string} [timezone=this.timezone] - The timezone for formatting timestamps.
* @returns {ApplicationLogger} A new logger instance.
*/
create(app, timezone = this.timezone) {
return new ApplicationLogger(this.service, app, timezone);
}
/**
* Add a block to the logger instance.
* @param {string} key - The key for the block.
* @param {string} [value=''] - The value for the block.
* @param {string} [color=''] - The color for the block value.
* @returns {ApplicationLogger} A new logger instance with the added block.
*/
block(key, value = '', color = '') {
const newBlocks = { ...this.blocks, [key]: { value, color } };
return new ApplicationLogger(this.service, this.app, this.timezone, newBlocks);
}
/**
* Log a message with a specific log level and optional color.
* @param {string} level - The log level (e.g., 'info', 'warn', 'error', 'debug').
* @param {string} message - The message to log.
* @param {string} [color=''] - The color for the message.
*/
log(level, message, color = '') {
const coloredMessage = color ? colors[color](message) : message;
this.logger.log(level, coloredMessage);
}
/**
* Log an info level message with optional color.
* @param {string} message - The message to log.
* @param {string} [color=''] - The color for the message.
*/
info(message, color = '') {
this.log('info', message, color);
}
/**
* Log a warn level message with optional color.
* @param {string} message - The message to log.
* @param {string} [color=''] - The color for the message.
*/
warn(message, color = '') {
this.log('warn', message, color);
}
/**
* Log an error level message with optional color.
* @param {string} message - The message to log.
* @param {string} [color=''] - The color for the message.
*/
error(message, color = '') {
this.log('error', message, color);
}
/**
* Log a debug level message with optional color.
* @param {string} message - The message to log.
* @param {string} [color=''] - The color for the message.
*/
debug(message, color = '') {
this.log('debug', message, color);
}
}
export default ApplicationLogger;