logger.js 2.54 KB
import moment from "moment";

export default {
	log: (...args) => {
		const req = args[0];
		if (typeof req === 'object' && req.hasOwnProperty("specialType")) {
			args[0] = req.headers.__reqId;
		}
		console.log(`\x1b[0m${getTime()} INFO ${toString(args).join('')}\x1b[0m`)
	},
	info: (...args) => {
		const req = args[0];
		if (typeof req === 'object' && req.hasOwnProperty("specialType")) {
			args[0] = req.headers.__reqId;
		}
		console.log(`\x1b[36m${getTime()} INFO ${toString(args).join('')}\x1b[0m`)
	},
	error: (...args) => {
		const req = args[0];
		if (typeof req === 'object' && req.hasOwnProperty("specialType")) {
			args[0] = req.headers.__reqId;
		}
		console.log(`\x1b[31m${getTime()} ERROR ${toString(args).join('')}\x1b[0m`)
	},
	warning: (...args) => {
		const req = args[0];
		if (typeof req === 'object' && req.hasOwnProperty("specialType")) {
			args[0] = req.headers.__reqId;
		}
		console.log(`\x1b[33m${getTime()} INFO ${toString(args).join('')}\x1b[0m`)
	},
	success: (...args) => {
		const req = args[0];
		if (typeof req === 'object' && req.hasOwnProperty("specialType")) {
			args[0] = req.headers.__reqId;
		}
		console.log(`\x1b[32m${getTime()} INFO ${toString(args).join('')}\x1b[0m`)
	},
	magenta: (...args) => {
		const req = args[0];
		if (typeof req === 'object' && req.hasOwnProperty("specialType")) {
			args[0] = req.headers.__reqId;
		}
		console.log(`\x1b[35m${getTime()} INFO ${toString(args).join('')}\x1b[0m`)
	},
	random: (...args) => {
		const req = args[0];
		if (typeof req === 'object' && req.hasOwnProperty("specialType")) {
			args[0] = req.headers.__reqId;
		}
		console.log((toString(args).join('').split('').map(item => '\x1b[' + randomColor() + 'm' + item + '\x1b[0m')).join('') + '\n')
	},
	db: (...args) => {
		const req = args[0];
		if (typeof req === 'object' && req.hasOwnProperty("specialType")) {
			args[0] = req.headers.__reqId;
		}
		console.log(`\x1b[35m${getTime()} INFO [Database Message] ${toString(args).join('')}\x1b[0m`)
	},
}
/**
 * Random color not duplicate next character
 */
let tempColor = null;
let randomColor = () => {
	if (tempColor != null) {
		const rand = Math.floor(Math.random() * (37 - 31) + 31);
		if (rand != tempColor) {
			tempColor = rand;
			return rand;
		} else {
			return randomColor();
		}
	} else {
		tempColor = Math.floor(Math.random() * (37 - 31) + 31);
		return tempColor;
	}
}

let toString = (list) => {
	return list.map(item => item.constructor.name == 'Object' || item.constructor.name == 'Array' ? JSON.stringify(item) : item);
}

let getTime = () => moment().format("YYYY-MM-DD HH:mm:ss:SSS");