1
0
auth.rxbn.de/bin/logs/module.js

95 lines
2.4 KiB
JavaScript
Raw Normal View History

2019-06-23 21:18:46 +00:00
/*
* This file is part of the authRxbn eco-system.
*
* (c) Ruben Meyer <contact@rxbn.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var methods = {};
let fs = require('fs');
let util = require('util');
2019-06-30 18:56:48 +00:00
// save new line to file
newLine = (prefix, obj) => {
let date = new Date(); // current date
let filename = global['gds'].cfg.log.filename(); // filename
2019-06-30 18:59:32 +00:00
let dir = global['gds'].cfg.log.directory(); // directory
2019-06-30 18:56:48 +00:00
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"
}
}
2019-06-23 21:18:46 +00:00
// LOG | INFO
methods.log = (...data) => {
global['modules'].cli.log.apply(global['modules'].cli, data);
if(data.length == 1) data = data[0];
newLine(" [LOG]", data);
};
methods.info = methods.log;
// WARNING
methods.warn = (...data) => {
global['modules'].cli.log.apply(global['modules'].cli, data);
if(data.length == 1) data = data[0];
newLine(" [WARN]", data);
};
// ERROR
methods.error = (...data) => {
global['modules'].cli.log.apply(global['modules'].cli, data);
if(data.length == 1) data = data[0];
newLine("[ERROR]", data);
};
methods.err = methods.error;
// DEBUG
methods.debug = (...data) => {
if(global['gds'].debug) {
global['modules'].cli.log.apply(global['modules'].cli, data);
if(data.length == 1) data = data[0];
newLine("[DEBUG]", data);
}
};
module.exports = methods;