slideshow.io/lib/log.js

146 lines
3.2 KiB
JavaScript

var express = require('express');
var http = require('http');
var yargs = require('yargs');
var argv = yargs.argv;
var log = {};
var Color = {
DEFAULT:0,
BLACK:1,
RED:2,
GREEN:3,
YELLOW:4,
BLUE:5,
MAGENTA:6,
CYAN:7,
ORANGE:8
}
function getColorCode(c) {
switch (c) {
case Color.DEFAULT: return '\u001b[0m';
case Color.BLACK: return '\u001b[30m';
case Color.RED: return '\u001b[31m';
case Color.GREEN: return '\u001b[32m';
case Color.YELLOW: return '\u001b[33m';
case Color.BLUE: return '\u001b[34m';
case Color.MAGENTA: return '\u001b[35m';
case Color.CYAN: return '\u001b[36m';
case Color.ORANGE: return '\u001b[38;5;202m';
}
}
var isDev = require('express')().get('env') === 'development';
var write;
if (argv.nolisten || argv.n) {
write = function(elt, color) { }
} else if (isDev) {
write = function(elt, color) {
console.log(getColorCode(color) + elt + getColorCode(Color.DEFAULT));
}
} else {
write = function(elt, color) {
console.log(elt);
}
}
log.ready = function(msg) {
write('[RDY] ' + new Date() + ' ' + msg, Color.GREEN);
}
log.request = function(req, res, time) {
if (req.headers['x-forwarded-for'] !== undefined || isDev) {
var isStatic = req.url.substr(0, 7) === '/static' || req.url === '/favicon.ico';
write(
'[REQ] ' + new Date() + ' ' +
(req.headers['x-forwarded-for'] || req.connection.remoteAddress) +
(time !== undefined ? (' in ' + (" " + time).slice(-6) + ' ms') : '') +
' : ' + (isStatic && req.url !== '/favicon.ico' ? '/static' + req.url : req.url),
isStatic ? Color.YELLOW : Color.CYAN
);
}
}
log.socket = {};
log.socket.connection = function(socket, isTest) {
write(
'[SOK] ' + new Date() + ' ' +
(socket.handshake.headers['x-forwarded-for'] || socket.handshake.address) + (isTest ? ' test' : '') + ' connection',
Color.MAGENTA
);
}
log.socket.disconnect = function(socket, isTest) {
write(
'[SOK] ' + new Date() + ' ' +
(socket.handshake.headers['x-forwarded-for'] || socket.handshake.address) + (isTest ? ' test' : '') + ' disconnect',
Color.MAGENTA
);
}
log.dberror = function(error) {
write(
'[DBE] ' + new Date() + ' ' + error,
Color.RED
);
}
log.prefetcherror = function(error) {
write(
'[PFE] ' + new Date() + ' ' + error,
Color.RED
);
}
log.mailerror = function(error) {
write(
'[MLE] ' + new Date() + ' ' + error,
Color.RED
);
}
log.debug = function(info, force) {
if (isDev || force === true) {
write(
'[DBG] ' + (info !== undefined ? info : ''),
Color.YELLOW
);
}
}
log.pugerror = function(error) {
write(
'[PER] ' + new Date() + ' ' + error,
Color.RED
);
}
log.warning = function(message) {
write(
'[WRN] ' + new Date() + ' ' + message,
Color.ORANGE
);
}
log.faceerror = function(message) {
write(
'[FER] ' + new Date() + ' ' + message,
Color.RED
);
}
module.exports = log;