1
0
mirror of https://git.stamm.me/OpenServer/NodeLogging.git synced 2024-09-28 04:17:37 +00:00
nodelogging/out/index.js
2018-09-28 12:37:13 +02:00

380 lines
12 KiB
JavaScript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util = require("util");
const fs = require("fs");
const events_1 = require("events");
const path = require("path");
const lock_1 = require("./lock");
exports.Colors = {
Reset: "\x1b[0m",
Bright: "\x1b[1m",
Dim: "\x1b[2m",
Underscore: "\x1b[4m",
Blink: "\x1b[5m",
Reverse: "\x1b[7m",
Hidden: "\x1b[8m",
FgBlack: "\x1b[30m",
FgRed: "\x1b[31m",
FgGreen: "\x1b[32m",
FgYellow: "\x1b[33m",
FgBlue: "\x1b[34m",
FgMagenta: "\x1b[35m",
FgCyan: "\x1b[36m",
FgWhite: "\x1b[37m",
BgBlack: "\x1b[40m",
BgRed: "\x1b[41m",
BgGreen: "\x1b[42m",
BgYellow: "\x1b[43m",
BgBlue: "\x1b[44m",
BgMagenta: "\x1b[45m",
BgCyan: "\x1b[46m",
BgWhite: "\x1b[47m"
};
const maxFileSize = 500000000;
const OriginalErrorStackFunction = Error.prototype.prepareStackTrace;
class LoggingBase {
constructor(options) {
this.writeLock = new lock_1.default();
this.setted_up = false;
this.fileSize = 0;
this.errorSize = 0;
this.queue = new Array();
this.events = new events_1.EventEmitter();
let opt;
if (!options)
opt = {};
else if (typeof options === "string") {
opt = { name: options };
}
else {
opt = options;
}
if (opt.name) {
if (opt.logfile === undefined) {
opt.logfile = `./logs/all.${opt.name}.log`;
}
if (opt.errorfile === undefined) {
opt.errorfile = `./logs/error.${opt.name}.log`;
}
}
this.config = Object.assign({
name: undefined,
console_out: true,
logfile: "./logs/all.log",
errorfile: "./logs/error.log"
}, opt);
for (let key in this) {
if (typeof this[key] === "function")
this[key] = this[key].bind(this);
}
}
get console_out() {
return this.config.console_out;
}
set console_out(value) {
this.config.console_out = value;
}
async waitForSetup() {
(await this.writeLock.getLock()).release();
}
async setup() {
this.setted_up = true;
let lock = await this.writeLock.getLock();
if (this.config.logfile) {
let f = await this.initializeFile(this.config.logfile, true);
this.fileStream = f.stream;
this.fileSize = f.size;
}
if (this.config.errorfile) {
let f = await this.initializeFile(this.config.errorfile, false);
this.errorStream = f.stream;
this.errorSize = f.size;
}
lock.release();
this.checkQueue();
}
debug(...message) {
this.message(LoggingTypes.Debug, message);
}
log(...message) {
this.message(LoggingTypes.Log, message);
}
warning(...message) {
this.message(LoggingTypes.Warning, message);
}
logWithCustomColors(type, colors, ...message) {
this.message(type, message, colors);
}
error(error) {
if (!error)
error = "Empty ERROR was passed, so no informations available";
if (typeof error === "string") {
let e = new Error();
this.message(LoggingTypes.Error, [error, "\n", e.stack]);
}
else {
this.message(LoggingTypes.Error, [error.message, "\n", error.stack], undefined, getCallerFromExisting(error));
}
}
errorMessage(...message) {
this.message(LoggingTypes.Error, message);
}
async message(type, message, customColors, caller) {
var consoleLogFormat = exports.Colors.Reset;
if (!customColors) {
switch (type) {
case LoggingTypes.Log:
//m += FgWhite + BgBlack;
break;
case LoggingTypes.Error:
consoleLogFormat += exports.Colors.FgRed; //FgWhite + BgRed + FgWhite;
break;
case LoggingTypes.Debug:
consoleLogFormat += exports.Colors.FgCyan;
break;
case LoggingTypes.Warning:
consoleLogFormat += exports.Colors.FgYellow;
break;
}
}
else {
consoleLogFormat += customColors;
}
var mb = "";
if (typeof message === "string") {
mb = message;
}
else {
message.forEach(e => {
if (typeof e !== "string")
e = util.inspect(e, false, null);
if (e.endsWith("\n")) {
mb += e;
}
else {
mb += e + " ";
}
});
}
let file = caller || getCallerFile();
let date = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
let prefix = `[${LoggingTypes[type]}][${file.file}:${file.line}][${date}]: `;
let message_lines = mb.split("\n").map(line => prefix + line);
if (this.config.console_out) {
let prefix = "";
if (this.config.name)
prefix = `[${this.config.name}]`;
message_lines.forEach(line => console.log(consoleLogFormat + prefix + line + exports.Colors.Reset));
}
let m = message_lines.join("\n");
let index = m.indexOf("\x1b");
while (index >= 0) {
m = m.substring(0, index) + m.substring(index + 5, m.length);
index = m.indexOf("\x1b");
}
m = m.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, "");
this.writeMessageToFile(m, type === LoggingTypes.Error);
this.events.emit("message", { type: type, message: mb });
}
writeMessageToFile(message, error) {
if (this.setted_up && (!this.fileStream || (error && !this.errorStream)))
return;
this.queue.push({ message: message.replace("\n", " "), error: error });
this.checkQueue();
}
async checkQueue() {
try {
if (this.writeLock.locked)
return;
if (this.queue.length <= 0)
return;
if (!this.setted_up)
return this.setup();
let lock = await this.writeLock.getLock();
var message = this.queue.shift();
message.message += "\n";
let data = new Buffer(message.message, "utf8");
await this.writeToLogFile(data);
if (message.error)
await this.writeToErrorFile(data);
lock.release();
if (this.queue.length > 0)
this.checkQueue();
}
catch (e) {
console.log(e);
}
}
async writeToLogFile(data) {
if (data.byteLength < maxFileSize && this.fileSize + data.byteLength > maxFileSize) {
let f = await this.initializeFile(this.config.logfile, true);
this.fileStream = f.stream;
this.fileSize = f.size;
}
this.fileSize += data.byteLength;
this.fileStream.write(data);
}
async writeToErrorFile(data) {
if (data.byteLength < maxFileSize && this.errorSize + data.byteLength > maxFileSize) {
let f = await this.initializeFile(this.config.errorfile, true);
this.errorStream = f.stream;
this.errorSize = f.size;
}
this.errorSize += data.byteLength;
this.errorStream.write(data);
}
async initializeFile(file, new_file = true) {
try {
const folder = path.dirname(file);
if (folder) {
if (!await fsExists(folder)) {
await fsMkDir(folder).catch(() => { }); //Could happen, if two seperate logger want to create folder so ignoring
}
}
let size = 0;
if (await fsExists(file)) {
let stats = await fsStat(file);
if (new_file || stats.size > maxFileSize) {
if (await fsExists(file + ".old"))
await fsUnlink(file + ".old");
await fsMove(file, file + ".old");
}
else {
size = stats.size;
}
}
return { stream: fs.createWriteStream(file, { flags: "a" }), size: size };
}
catch (e) {
console.log(e);
}
return { size: 0, stream: undefined };
}
}
exports.LoggingBase = LoggingBase;
exports.Logging = undefined;
if (process.env.LOGGING_NO_DEFAULT !== "true") {
exports.Logging = new LoggingBase();
}
exports.default = exports.Logging;
function fsUnlink(path) {
return new Promise((resolve, reject) => {
fs.unlink(path, (err) => {
if (err)
reject(err);
else
resolve();
});
});
}
function fsStat(path) {
return new Promise((resolve, reject) => {
fs.stat(path, (err, stats) => {
if (err)
reject(err);
else
resolve(stats);
});
});
}
function fsMove(oldPath, newPath) {
return new Promise((resolve, reject) => {
let callback = (err) => {
if (err)
reject(err);
else
resolve();
};
fs.rename(oldPath, newPath, function (err) {
if (err) {
if (err.code === 'EXDEV') {
copy();
}
else {
callback(err);
}
return;
}
callback();
});
function copy() {
var readStream = fs.createReadStream(oldPath);
var writeStream = fs.createWriteStream(newPath);
readStream.on('error', callback);
writeStream.on('error', callback);
readStream.on('close', function () {
fs.unlink(oldPath, callback);
});
readStream.pipe(writeStream);
}
});
}
function fsExists(path) {
return new Promise((resolve, reject) => {
fs.exists(path, resolve);
});
}
function fsMkDir(path) {
return new Promise((resolve, reject) => {
fs.mkdir(path, (err) => err ? reject(err) : resolve());
});
}
function getStack() {
// Save original Error.prepareStackTrace
let origPrepareStackTrace = Error.prepareStackTrace;
// Override with function that just returns `stack`
Error.prepareStackTrace = function (_, stack) {
return stack;
};
// Create a new `Error`, which automatically gets `stack`
let err = new Error();
// Evaluate `err.stack`, which calls our new `Error.prepareStackTrace`
let stack = err.stack;
// Restore original `Error.prepareStackTrace`
Error.prepareStackTrace = origPrepareStackTrace;
// Remove superfluous function call on stack
stack.shift(); // getStack --> Error
return stack;
}
function getCallerFile() {
try {
let stack = getStack();
let current_file = stack.shift().getFileName();
while (stack.length) {
let caller_file = stack.shift();
const util = require("util");
if (current_file !== caller_file.getFileName())
return {
file: path.basename(caller_file.getFileName()),
line: caller_file.getLineNumber()
};
}
}
catch (err) { }
return { file: undefined, line: 0 };
}
function getCallerFromExisting(err) {
let lines = err.stack.split("\n");
let current = path.basename(__filename);
lines.shift(); // removing first line
while (lines.length > 0) {
let line = lines.shift();
let matches = line.match(/[a-zA-Z_-]+[.][a-zA-Z_-]+[:][0-9]+/g);
if (matches && matches.length > 0) {
let [f, line] = matches[0].split(":");
if (f != current) {
return {
file: f, line: Number(line)
};
}
}
}
}
var LoggingTypes;
(function (LoggingTypes) {
LoggingTypes[LoggingTypes["Log"] = 0] = "Log";
LoggingTypes[LoggingTypes["Warning"] = 1] = "Warning";
LoggingTypes[LoggingTypes["Error"] = 2] = "Error";
LoggingTypes[LoggingTypes["Debug"] = 3] = "Debug";
})(LoggingTypes = exports.LoggingTypes || (exports.LoggingTypes = {}));
//# sourceMappingURL=index.js.map