UNPKG

zb-log-server

Version:
85 lines (71 loc) 1.88 kB
/* eslint-disable no-console */ const chalk = require('chalk'); /** * Log level to color. * @type {Object} */ const logLevelColors = { '[LOG]': chalk.white, '[DEBUG]': chalk.blue, '[INFO]': chalk.green, '[WARN]': chalk.yellow, '[ERROR]': chalk.magenta, '[TIME]': chalk.grey }; /** * Max length of log level string. Used for pad log levels. * @type {number} */ const maxLevelLength = Math.max(...Object.keys(logLevelColors).map((str) => str.length)); /** * @param {Date} date * @return {string} */ const formatTime = (date) => { const str = String(date); const ms = ('' + (date.getTime() % 1000)).padEnd(3, '0'); return /(\d{2}:\d{2}:\d{2})/.exec(str)[0] + '.' + ms; }; /** * @param {string} level * @param {string} str * @return {string} */ const colorizeByLevel = (level, str) => logLevelColors[level](str); /** * @param {http.ClientRequest} req * @param {http.ServerResponse} res */ const zbLogMiddleware = (req, res) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); if (req.method === 'POST') { let body = ''; req.on('data', (data) => { body += data; }); req.on('end', () => { const exp = /^(\[\w+]) (\d+)/; if (exp.test(body)) { const parts = exp.exec(body); let level = parts[1] || ''; const sendTime = parts[2] || 0; body = body.substr(parts[0].length); level = colorizeByLevel(level, level.padEnd(maxLevelLength)); console.log( chalk.gray(formatTime(new Date())), chalk.cyan(formatTime(new Date(+sendTime))), level, body ); } else { console.error('zbLogMiddleware parse fail', body); } res.end('Ok\n'); }); } else { res.statusCode = 405; // Method not allowed res.end('Use POST, Luke.\n', 'utf-8'); } }; module.exports = zbLogMiddleware;