-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.js
67 lines (57 loc) · 1.65 KB
/
logger.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
var fs = require("fs");
var os = require('os');
/* VARIABLES */
var debug = false;
var logFile = "access.log";
/* FUNCTIONS */
function logInfo(message) {
var infoMessage = "[INFO] " + getDateString() + message;
console.log(infoMessage);
logToFile(infoMessage);
}
exports.logInfo = logInfo;
function logSevere(message) {
var severeMessage = "[SEVERE] " + getDateString() + message;
console.log(severeMessage);
console.trace();
logToFile(severeMessage);
logToFile(console.trace());
}
exports.logSevere = logSevere;
function logDebug(message) {
if(debug === true) {
var debugMessage = "[DEBUG] " + getDateString() + message;
console.log(debugMessage);
logToFile(debugMessage);
}
}
exports.logDebug = logDebug;
function logRequest(request) {
var clientIp = request.headers['x-forwarded-for'] || request.connection.remoteAddress;
logInfo(clientIp + " requested '" + request.originalUrl + "' User-agent: " + request.headers["user-agent"]);
}
exports.logRequest = logRequest;
function setDebug(active) {
debug = active;
}
exports.setDebug = setDebug;
function logToFile(message) {
fs.appendFile(__dirname + "/" + logFile, message + os.EOL, function(error) {
if(error) {
logger.logSevere("logToFile: " + error);
}
});
}
function getDateString() {
var date = new Date();
return date.getUTCFullYear() + "-"
+ padZeros(date.getUTCMonth(), 2) + "-"
+ padZeros(date.getUTCDay(), 2) + "_"
+ padZeros(date.getUTCHours(), 2) + ":"
+ padZeros(date.getUTCMinutes(),2) + ":"
+ padZeros(date.getUTCSeconds(),2) + " ";
}
function padZeros(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}