1
0
mirror of https://git.stamm.me/OpenServer/NodeLogging.git synced 2024-11-15 06:31:05 +00:00
nodelogging/src/index.ts

389 lines
11 KiB
TypeScript
Raw Normal View History

2017-08-23 14:45:03 +00:00
import * as util from "util";
import * as fs from "fs";
import { EventEmitter } from "events";
import * as path from "path";
2018-08-09 17:52:01 +00:00
import Lock from "./lock";
2017-08-23 14:45:03 +00:00
const Reset = "\x1b[0m"
const Bright = "\x1b[1m"
const Dim = "\x1b[2m"
const Underscore = "\x1b[4m"
const Blink = "\x1b[5m"
const Reverse = "\x1b[7m"
const Hidden = "\x1b[8m"
const FgBlack = "\x1b[30m"
const FgRed = "\x1b[31m"
const FgGreen = "\x1b[32m"
const FgYellow = "\x1b[33m"
const FgBlue = "\x1b[34m"
const FgMagenta = "\x1b[35m"
const FgCyan = "\x1b[36m"
const FgWhite = "\x1b[37m"
const BgBlack = "\x1b[40m"
const BgRed = "\x1b[41m"
const BgGreen = "\x1b[42m"
const BgYellow = "\x1b[43m"
const BgBlue = "\x1b[44m"
const BgMagenta = "\x1b[45m"
const BgCyan = "\x1b[46m"
const BgWhite = "\x1b[47m"
2018-02-18 15:00:16 +00:00
const maxFileSize = 500000000;
const OriginalErrorStackFunction = (<any>Error.prototype).prepareStackTrace
2018-08-09 17:52:01 +00:00
export interface LoggingBaseOptions {
logfile: string;
errorfile: string;
console_out: boolean;
}
2017-08-23 14:45:03 +00:00
2018-08-09 17:52:01 +00:00
export class LoggingBase {
private config: LoggingBaseOptions;
private writeLock = new Lock();
private fileStream: fs.WriteStream;
private errorStream: fs.WriteStream;
private fileSize: number = 0;
private errorSize: number = 0;
private queue = new Array<{ message: string, error: boolean }>();
constructor(options?: Partial<LoggingBaseOptions>) {
if (!options) options = {};
this.config = Object.assign(<LoggingBaseOptions>{
console_out: true,
logfile: "./logs/all.log",
errorfile: "./logs/error.log"
}, options);
this.setup();
}
2017-08-23 14:45:03 +00:00
2018-08-09 17:52:01 +00:00
get console_out() {
return this.config.console_out;
}
2017-08-23 14:45:03 +00:00
2018-08-09 17:52:01 +00:00
set console_out(value) {
this.config.console_out = value;
}
2018-08-09 17:52:01 +00:00
public async waitForSetup() {
(await this.writeLock.getLock()).release();
2017-08-23 14:45:03 +00:00
}
2018-08-09 17:52:01 +00:00
private async setup() {
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, true);
this.errorStream = f.stream;
this.errorSize = f.size;
}
lock.release();
this.checkQueue();
2017-08-23 14:45:03 +00:00
}
2018-08-09 17:52:01 +00:00
events: EventEmitter = new EventEmitter();
debug(...message: any[]) {
this.message(LoggingTypes.Debug, message);
2017-08-23 14:45:03 +00:00
}
2018-08-09 17:52:01 +00:00
log(...message: any[]) {
this.message(LoggingTypes.Log, message);
2017-08-23 14:45:03 +00:00
}
2018-08-09 17:52:01 +00:00
warning(...message: any[]) {
this.message(LoggingTypes.Warning, message);
2017-09-16 17:21:22 +00:00
}
2018-08-09 17:52:01 +00:00
logWithCustomColors(type: LoggingTypes, colors: string, ...message: any[]) {
this.message(type, message, colors);
}
error(error: Error | string) {
2017-08-23 14:45:03 +00:00
if (typeof error === "string") {
let e = new Error()
2018-08-09 17:52:01 +00:00
this.message(LoggingTypes.Error, [error, ":", e.stack]);
2018-07-01 11:05:34 +00:00
} else {
2018-08-09 17:52:01 +00:00
this.message(LoggingTypes.Error, [error.name, ":", error.message, ":", error.stack]);
2017-08-23 14:45:03 +00:00
}
}
2018-08-09 17:52:01 +00:00
errorMessage(...message: any[]) {
this.message(LoggingTypes.Error, message);
2017-08-23 14:45:03 +00:00
}
2018-08-09 17:52:01 +00:00
private async message(type: LoggingTypes, message: any[] | string, customColors?: string) {
2017-08-23 14:45:03 +00:00
var consoleLogFormat = Reset;
2017-09-16 17:21:22 +00:00
if (!customColors) {
switch (type) {
case LoggingTypes.Log:
//m += FgWhite + BgBlack;
break;
case LoggingTypes.Error:
consoleLogFormat += FgRed;//FgWhite + BgRed + FgWhite;
break;
case LoggingTypes.Debug:
consoleLogFormat += FgCyan;
break;
case LoggingTypes.Warning:
consoleLogFormat += FgYellow;
break;
}
} else {
consoleLogFormat += customColors;
2017-08-23 14:45:03 +00:00
}
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 = getCallerFile()
let date = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
2018-08-09 17:52:01 +00:00
let prefix = `[${LoggingTypes[type]}][${file.file}:${file.line}][${date}]: `;
let message_lines = mb.split("\n").map(line => prefix + line);
2018-08-09 17:52:01 +00:00
if (this.config.console_out) message_lines.forEach(line => console.log(consoleLogFormat + line + Reset));
let m = message_lines.join("\n");
let index = m.indexOf("\x1b");
while (index >= 0) {
2018-04-09 18:02:34 +00:00
m = m.substring(0, index) + m.substring(index + 5, m.length);
index = m.indexOf("\x1b");
}
2018-04-09 17:57:39 +00:00
m = m.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, "");
2018-08-09 17:52:01 +00:00
this.writeMessageToFile(m, type === LoggingTypes.Error);
this.events.emit("message", { type: type, message: mb });
2017-08-23 14:45:03 +00:00
}
2018-08-09 17:52:01 +00:00
private writeMessageToFile(message: string, error?: boolean) {
if (!this.writeLock.locked && !this.fileStream && !(error || this.errorStream)) return;
this.queue.push({ message: message.replace("\n", " "), error: error });
this.checkQueue();
2017-08-23 14:45:03 +00:00
}
2018-08-09 17:52:01 +00:00
private async checkQueue() {
2018-02-18 15:00:16 +00:00
try {
2018-08-09 17:52:01 +00:00
if (this.writeLock.locked) return;
if (this.queue.length <= 0) return;
let lock = await this.writeLock.getLock();
var message = this.queue.shift();
2018-02-18 15:00:16 +00:00
message.message += "\n";
let data = new Buffer(message.message, "utf8");
2018-08-09 17:52:01 +00:00
await this.writeToLogFile(data);
if (message.error) await this.writeToErrorFile(data);
lock.release();
if (this.queue.length > 0) this.checkQueue();
2018-02-18 15:00:16 +00:00
} catch (e) {
console.log(e)
}
2017-08-23 14:45:03 +00:00
}
2018-08-09 17:52:01 +00:00
private async writeToLogFile(data: Buffer) {
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);
}
private async writeToErrorFile(data: Buffer) {
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);
}
private async initializeFile(file: string, new_file = true): Promise<{ stream: fs.WriteStream, size: number }> {
2017-08-23 14:45:03 +00:00
try {
await new Promise((resolve, reject) => {
2018-08-09 17:52:01 +00:00
const folder = path.dirname(file);
if (folder)
fs.exists(folder, (exists) => {
if (!exists) {
fs.mkdir(folder, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
} else resolve();
});
2017-08-23 14:45:03 +00:00
});
2018-08-09 17:52:01 +00:00
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")
2018-02-18 15:00:16 +00:00
} else {
2018-08-09 17:52:01 +00:00
size = stats.size;
2018-02-18 15:00:16 +00:00
}
}
2018-08-09 17:52:01 +00:00
return { stream: fs.createWriteStream(file, { flags: "a" }), size: size };
// if (await fsExists(this.logFileLocation + "error.log")) {
// let stats = await fsStat(this.logFileLocation + "error.log")
// if (stats.size > maxFileSize) {
// if (await fsExists(this.logFileLocation + "error.log.old"))
// await fsUnlink(this.logFileLocation + "error.log.old");
// await fsMove(this.logFileLocation + "error.log", this.logFileLocation + "error.log.old")
// } else {
// this.errorSize = stats.size;
// }
// }
// this.fileStream = fs.createWriteStream(this.logFileLocation + "all.log", { flags: "a" });
// this.errorStream = fs.createWriteStream(this.logFileLocation + "error.log", { flags: "a" });
// this.writing = false;
// this.checkQueue();
2017-08-23 14:45:03 +00:00
} catch (e) {
console.log(e);
}
2018-08-09 17:52:01 +00:00
return { size: 0, stream: undefined };
2017-08-23 14:45:03 +00:00
}
}
2018-08-09 17:52:01 +00:00
export const Logging = new LoggingBase();
export default Logging;
2018-02-18 15:00:16 +00:00
function fsUnlink(path) {
return new Promise((resolve, reject) => {
fs.unlink(path, (err) => {
if (err) reject(err);
else resolve();
})
})
}
function fsStat(path: string) {
return new Promise<fs.Stats>((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<boolean>((resolve, reject) => {
fs.exists(path, resolve);
});
}
function fsMkDir(path) {
return new Promise((resolve, reject) => {
fs.exists(path, resolve);
});
}
function getStack() {
// Save original Error.prepareStackTrace
let origPrepareStackTrace = (<any>Error).prepareStackTrace;
// Override with function that just returns `stack`
(<any>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: any[] = <any>err.stack;
// Restore original `Error.prepareStackTrace`
(<any>Error).prepareStackTrace = origPrepareStackTrace;
// Remove superfluous function call on stack
stack.shift(); // getStack --> Error
return stack
}
function getCallerFile() {
2017-08-23 14:45:03 +00:00
try {
let stack = getStack()
2017-08-23 14:45:03 +00:00
let current_file = stack.shift().getFileName();
2017-08-23 14:45:03 +00:00
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()
};
2017-08-23 14:45:03 +00:00
}
} catch (err) { }
return { file: undefined, line: 0 };
2017-08-23 14:45:03 +00:00
}
export enum LoggingTypes {
Log,
Warning,
Error,
Debug
}