112 lines
2.5 KiB
JavaScript
112 lines
2.5 KiB
JavaScript
|
// requirements
|
||
|
const config = require("../config.json");
|
||
|
// third party requirements
|
||
|
const moment = require("moment");
|
||
|
|
||
|
// constants
|
||
|
const LOG_PREFIX_DEBUG = "debug";
|
||
|
const LOG_PREFIX_INFO = "info";
|
||
|
const LOG_PREFIX_WARNING = "warning";
|
||
|
const LOG_PREFIX_ERROR = "error";
|
||
|
const LOGLEVEL_DEBUG = 0;
|
||
|
const LOGLEVEL_INFO = 1;
|
||
|
const LOGLEVEL_WARNING = 2;
|
||
|
const LOGLEVEL_ERROR = 3;
|
||
|
|
||
|
// set loglevel on "require"
|
||
|
const loglevel = function() {
|
||
|
switch (config.log.level) {
|
||
|
case LOG_PREFIX_DEBUG:
|
||
|
case LOGLEVEL_DEBUG:
|
||
|
return LOGLEVEL_DEBUG;
|
||
|
case LOG_PREFIX_INFO:
|
||
|
case LOGLEVEL_INFO:
|
||
|
return LOGLEVEL_INFO;
|
||
|
case LOG_PREFIX_WARNING:
|
||
|
case LOGLEVEL_WARNING:
|
||
|
return LOGLEVEL_WARNING;
|
||
|
case LOG_PREFIX_ERROR:
|
||
|
case LOGLEVEL_ERROR:
|
||
|
return LOGLEVEL_ERROR;
|
||
|
default:
|
||
|
return LOGLEVEL_INFO;
|
||
|
}
|
||
|
}();
|
||
|
|
||
|
// log a http request
|
||
|
function logRequest(request) {
|
||
|
let message = "[" + request.method + "] url: \"" + request.url + "\"";
|
||
|
let counter = 1;
|
||
|
for (let param in request.body) {
|
||
|
message += ", parameter " + counter + ": \"" + param + "=" + request.body[param] + "\"";
|
||
|
counter++;
|
||
|
}
|
||
|
debug(message.trim());
|
||
|
}
|
||
|
|
||
|
// prefix log with "info"
|
||
|
function info(message) {
|
||
|
if (loglevel > LOGLEVEL_INFO) {
|
||
|
return;
|
||
|
}
|
||
|
trace(message);
|
||
|
}
|
||
|
|
||
|
// prefix log with "info"
|
||
|
function warn(message) {
|
||
|
if (loglevel > LOGLEVEL_WARNING) {
|
||
|
return;
|
||
|
}
|
||
|
trace(message, "warning");
|
||
|
}
|
||
|
|
||
|
// prefix log with "debug"
|
||
|
function debug(message) {
|
||
|
if (loglevel > LOGLEVEL_DEBUG) {
|
||
|
return;
|
||
|
}
|
||
|
trace(message, "debug");
|
||
|
}
|
||
|
|
||
|
// prefix log with "error"
|
||
|
function error(message) {
|
||
|
if (loglevel > LOGLEVEL_ERROR) {
|
||
|
return;
|
||
|
}
|
||
|
trace(message, "error");
|
||
|
}
|
||
|
|
||
|
// default logging function
|
||
|
function trace(message, prefix) {
|
||
|
if (message === undefined || message === null || message.length === 0) {
|
||
|
return;
|
||
|
}
|
||
|
if (prefix === undefined || prefix === null || prefix.length === 0) {
|
||
|
prefix = "info";
|
||
|
}
|
||
|
let print;
|
||
|
switch (prefix) {
|
||
|
case "error":
|
||
|
print = console.error;
|
||
|
break;
|
||
|
case "debug":
|
||
|
print = console.debug;
|
||
|
break;
|
||
|
case "warning":
|
||
|
print = console.warn;
|
||
|
break;
|
||
|
default:
|
||
|
print = console.log;
|
||
|
}
|
||
|
message = moment().format(config.server.timestamp) + " | " + prefix + " > " + message;
|
||
|
print(message);
|
||
|
}
|
||
|
|
||
|
// exports
|
||
|
module.exports = {
|
||
|
info,
|
||
|
warn,
|
||
|
debug,
|
||
|
error,
|
||
|
logRequest
|
||
|
};
|