Spaces:
Paused
Paused
Upload logger.js
Browse files
logger.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import chalk from 'chalk';
|
| 2 |
+
import moment from 'moment';
|
| 3 |
+
|
| 4 |
+
const LogLevel = {
|
| 5 |
+
INFO: 'INFO',
|
| 6 |
+
WARN: 'WARN',
|
| 7 |
+
ERROR: 'ERROR',
|
| 8 |
+
DEBUG: 'DEBUG'
|
| 9 |
+
};
|
| 10 |
+
|
| 11 |
+
class Logger {
|
| 12 |
+
static formatMessage(level, message) {
|
| 13 |
+
const timestamp = moment().format('YYYY-MM-DD HH:mm:ss');
|
| 14 |
+
|
| 15 |
+
switch(level) {
|
| 16 |
+
case LogLevel.INFO:
|
| 17 |
+
return chalk.blue(`[${timestamp}] [${level}] ${message}`);
|
| 18 |
+
case LogLevel.WARN:
|
| 19 |
+
return chalk.yellow(`[${timestamp}] [${level}] ${message}`);
|
| 20 |
+
case LogLevel.ERROR:
|
| 21 |
+
return chalk.red(`[${timestamp}] [${level}] ${message}`);
|
| 22 |
+
case LogLevel.DEBUG:
|
| 23 |
+
return chalk.gray(`[${timestamp}] [${level}] ${message}`);
|
| 24 |
+
default:
|
| 25 |
+
return message;
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
static info(message, context) {
|
| 30 |
+
console.log(this.formatMessage(LogLevel.INFO, context ? `[${context}] ${message}` : message));
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
static warn(message, context) {
|
| 34 |
+
console.warn(this.formatMessage(LogLevel.WARN, context ? `[${context}] ${message}` : message));
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
static error(message, context, error = null) {
|
| 38 |
+
const errorMessage = error ? ` - ${error.message}` : '';
|
| 39 |
+
console.error(this.formatMessage(LogLevel.ERROR, `${context ? `[${context}] ` : ''}${message}${errorMessage}`));
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
static debug(message, context) {
|
| 43 |
+
if (process.env.NODE_ENV === 'development') {
|
| 44 |
+
console.debug(this.formatMessage(LogLevel.DEBUG, context ? `[${context}] ${message}` : message));
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
static requestLogger(req, res, next) {
|
| 49 |
+
const startTime = Date.now();
|
| 50 |
+
|
| 51 |
+
res.on('finish', () => {
|
| 52 |
+
const duration = Date.now() - startTime;
|
| 53 |
+
const logMessage = `${req.method} ${req.path} - ${res.statusCode} (${duration}ms)`;
|
| 54 |
+
|
| 55 |
+
if (res.statusCode >= 400) {
|
| 56 |
+
Logger.error(logMessage, undefined, 'HTTP');
|
| 57 |
+
} else {
|
| 58 |
+
Logger.info(logMessage, 'HTTP');
|
| 59 |
+
}
|
| 60 |
+
});
|
| 61 |
+
|
| 62 |
+
next();
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
export default Logger;
|