-
Notifications
You must be signed in to change notification settings - Fork 1
/
arc.js
119 lines (100 loc) · 2.43 KB
/
arc.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
var moment = require('moment');
var colors = require('colors');
var path = require('path');
var Promise = require('bluebird').Promise;
var fs = require('fs');
var configuration = {
max_log_level: 4,
log_to_file: false,
log_to_console: true,
timestamp_format: "M/D/YYYY HH:mm:ss:SSS"
};
var level_colors = {
"UNDEFINED": colors.white,
"ERROR": colors.red,
"FATAL": colors.magenta,
"WARN": colors.yellow,
"INFO": colors.cyan,
"DEBUG": colors.blue,
"SUCCESS": colors.green
};
var level_map = {
"UNDEFINED": 0,
"ERROR": 1,
"FATAL": 2,
"WARN": 3,
"INFO": 4,
"DEBUG": 5,
"SUCCESS": 6
};
var errorHandler;
function logToFile(line) {
if (configuration.hasOwnProperty("path")) {
fs.appendFile(configuration.path, line + "\n", function(err) {
if (err) {
console.log(err);
}
});
} else {
console.log("No path for log file specified in configuration...");
}
}
function getTimestamp() {
return moment().format(configuration.timestamp_format);
}
function log(message, level) {
if (typeof(level) !== "undefined" && typeof(level) === "string") {
level = level.toUpperCase();
if (level == "WARNING") {
level = "WARN";
}
} else {
level = "undefined";
}
if(typeof(message) === "object") {
try {
message = JSON.stringify(message);
} catch (err) {}
}
var f = level_colors[level] || function(v) {
return v;
};
var line = null;
if (configuration.max_log_level >= level_map[level]) {
line = f("[" + getTimestamp() + "] [" + level + "] " + message);
}
if (configuration.log_to_file && line !== null) {
logToFile(line);
}
if (configuration.log_to_console && line !== null) {
console.log(line);
}
}
function set(key, value) {
configuration[key] = value;
}
function error(message, errorObject) {
if (typeof(errorObject) === "undefined") {
// do nothing
} else {
var f = level_colors["ERROR"] || function(v) {
return v;
};
if (configuration.max_log_level >= level_map["ERROR"]) {
line = f("[" + getTimestamp() + "] [" + "ERROR" + "] " + message);
console.error(line, errorObject, errorObject.stack);
if (errorHandler) {
errorHandler(errorObject);
}
}
}
}
function setErrorHandler(handler) {
errorHandler = handler;
}
var logObject = {};
logObject.log = log;
logObject.error = error;
logObject.set = set;
logObject.setErrorHandler = setErrorHandler;
module.exports = logObject;