94 lines
2.2 KiB
JavaScript
94 lines
2.2 KiB
JavaScript
var methods = {};
|
|
let fs = require('fs');
|
|
let util = require('util');
|
|
|
|
var cfg = require(global['__dirname']+'/bin/config');
|
|
|
|
// save new line to file
|
|
newLine = (prefix, obj) => {
|
|
let date = new Date(); // current date
|
|
let filename = cfg.log.filename(); // filename
|
|
let dir = cfg.log.directory(); // directory
|
|
let path = dir + filename; // filepath
|
|
let fs_options = { // fs options for encoding, file mode and file flag
|
|
encoding: "utf8",
|
|
flag: "a+" // Open file for reading and appending. The file is created if it does not exist.
|
|
};
|
|
let date_string =
|
|
("0" + date.getUTCHours()).slice(-2) + ":" +
|
|
("0" + date.getUTCMinutes()).slice(-2) + ":" +
|
|
("0" + date.getUTCSeconds()).slice(-2);
|
|
|
|
// directory not existing; create directory
|
|
if(!fs.existsSync(dir)) {
|
|
fs.mkdir(dir, (err) => {
|
|
if(err) throw err;
|
|
});
|
|
}
|
|
|
|
|
|
// type matching
|
|
if(
|
|
typeof obj == "string" ||
|
|
typeof obj == "number" ||
|
|
typeof obj == "boolean"
|
|
) fs.appendFileSync(path, prefix + " " + date_string + " | " + obj + "\n", fs_options);
|
|
else
|
|
if(typeof obj == "object") {
|
|
let lines = JSON.stringify(obj, null, '\t'); // prettyprint obj as JSON
|
|
lines.split(/\r?\n/).forEach((line) => { // for each linebreak (\r | \n)
|
|
fs.appendFileSync(path, prefix + " " + date_string + " | " + line + "\n", fs_options);
|
|
});
|
|
} else {
|
|
// do nothing; not supported
|
|
// typeof obj == "symbol"
|
|
// typeof obj == "undefined"
|
|
// typeof obj == "function"
|
|
}
|
|
};
|
|
|
|
log = (fn, ...data) => {
|
|
if(data.length == 1) data = data[0];
|
|
|
|
fn.apply(null, data);
|
|
}
|
|
|
|
|
|
// LOG | INFO
|
|
methods.log = (...data) => {
|
|
log(console.log, data);
|
|
|
|
if(data.length == 1) data = data[0];
|
|
newLine(" [LOG]", data);
|
|
};
|
|
methods.info = methods.log;
|
|
|
|
// WARNING
|
|
methods.warn = (...data) => {
|
|
log(console.warn, data);
|
|
|
|
if(data.length == 1) data = data[0];
|
|
newLine(" [WARN]", data);
|
|
};
|
|
|
|
// ERROR
|
|
methods.error = (...data) => {
|
|
log(console.error, data);
|
|
|
|
if(data.length == 1) data = data[0];
|
|
newLine("[ERROR]", data);
|
|
};
|
|
methods.err = methods.error;
|
|
|
|
// DEBUG
|
|
methods.debug = (...data) => {
|
|
if(global['debug'] === true) {
|
|
log(console.log, data);
|
|
|
|
if(data.length == 1) data = data[0];
|
|
newLine("[DEBUG]", data);
|
|
}
|
|
};
|
|
|
|
module.exports = methods;
|