Improving logging

This commit is contained in:
Fabian 2019-04-04 22:22:52 -04:00
parent 11619948e3
commit 6065c37362
7 changed files with 304 additions and 55 deletions

14
package-lock.json generated
View File

@ -1,13 +1,13 @@
{
"name": "@hibas123/logging",
"version": "1.0.1",
"version": "2.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@hibas123/utils": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/@hibas123/utils/-/utils-2.0.2.tgz",
"integrity": "sha512-5yrpuuUv0YlL2BixiTQLta4EmPLMNZ9Waorymu6dbERiSIcBxDs8mcJDUDW7CGiewpHHQUMsqLycLUYPDx0LWw=="
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/@hibas123/utils/-/utils-2.0.5.tgz",
"integrity": "sha512-LI1Xw0QArpm0JqCUmuxRG7dgmjvyLPmJehcNRqHrWuCwmDRoPFe0PwmZsp8/saz6pCL2A4u0utVHWG2PG4lSyg=="
},
"abbrev": {
"version": "1.1.1",
@ -2801,9 +2801,9 @@
"dev": true
},
"typescript": {
"version": "3.3.4000",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-3.3.4000.tgz",
"integrity": "sha512-jjOcCZvpkl2+z7JFn0yBOoLQyLoIkNZAs/fYJkUG6VKy6zLPHJGfQJYFHzibB6GJaF/8QrcECtlQ5cpvRHSMEA==",
"version": "3.4.1",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-3.4.1.tgz",
"integrity": "sha512-3NSMb2VzDQm8oBTLH6Nj55VVtUEpe/rgkIzMir0qVoLyjDZlnMBva0U6vDiV3IH+sl/Yu6oP5QwsAQtHPmDd2Q==",
"dev": true
},
"undefsafe": {

View File

@ -1,6 +1,6 @@
{
"name": "@hibas123/logging",
"version": "1.1.0",
"version": "2.0.0",
"description": "",
"main": "out/index.js",
"types": "out/index.d.ts",
@ -21,9 +21,9 @@
"devDependencies": {
"concurrently": "^4.1.0",
"nodemon": "^1.18.10",
"typescript": "^3.3.4000"
"typescript": "^3.4.1"
},
"dependencies": {
"@hibas123/utils": "^2.0.2"
"@hibas123/utils": "^2.0.5"
}
}
}

View File

@ -1,37 +1,19 @@
import { Observable } from "@hibas123/utils";
import { ConsoleWriter } from "./consolewriter";
import inspect from "./inspect";
import { Adapter, LoggingTypes, Message } from "./types";
import { Adapter, LoggingTypes, Message, FormatConfig, DefaultFormatConfig, Format, FormatTypes, Colors, FormattedText, FormattedLine } from "./types";
export const Colors = {
Reset: "\x1b[0m",
Bright: "\x1b[1m",
Dim: "\x1b[2m",
Underscore: "\x1b[4m",
Blink: "\x1b[5m",
Reverse: "\x1b[7m",
Hidden: "\x1b[8m",
export function removeColors(text: string) {
text = text.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, "");
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"
// let index = text.indexOf("\x1b");
// while (index >= 0) {
// text = text.substring(0, index) + text.substring(index + 5, text.length);
// index = text.indexOf("\x1b");
// }
return text;
}
export interface LoggingBaseOptions {
/**
* Name will be prefixed on Console output and added to logfiles, if not specified here
@ -44,8 +26,14 @@ export interface LoggingBaseOptions {
}
export class LoggingBase {
private logFile: any;
private errorFile: any;
private _formatMap: FormatConfig = new DefaultFormatConfig();
public set formatMap(value: FormatConfig) {
this._formatMap = value;
}
private adapter: Adapter[] = [];
private adapter_init: Promise<void>[] = [];
@ -112,6 +100,10 @@ export class LoggingBase {
this.message(LoggingTypes.Warning, message);
}
warn(...message: any[]) {
this.message(LoggingTypes.Warning, message);
}
error(error: Error | string) {
if (!error) error = "Empty ERROR was passed, so no informations available";
if (typeof error === "string") {
@ -144,29 +136,52 @@ export class LoggingBase {
});
}
let lines = mb.split("\n");
let lines = removeColors(mb).split("\n");
let color = Colors.Reset;
let type_format: Format[] = [];
switch (type) {
case LoggingTypes.Log:
//m += FgWhite + BgBlack;
type_format = this._formatMap.log;
break;
case LoggingTypes.Error:
color += Colors.FgRed;//FgWhite + BgRed + FgWhite;
type_format = this._formatMap.error;
break;
case LoggingTypes.Debug:
color += Colors.FgCyan;
type_format = this._formatMap.debug;
break;
case LoggingTypes.Warning:
color += Colors.FgYellow;
type_format = this._formatMap.warning;
break;
}
let date = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
let prefix = `[${date}][${color}${LoggingTypes[type].toUpperCase().padEnd(5, " ")}${Colors.Reset}][${file}]: `;
let type_str = LoggingTypes[type].toUpperCase().padEnd(5, " ");
const prefix: FormattedText[] = [];
const a = (text: string, formats: Format[] = []) => {
prefix.push({
text,
formats
})
}
a("[");
a(date, this._formatMap.date);
a("][");
a(type_str, type_format);
if (file_raw.file) {
a("][");
a(file, this._formatMap.file);
}
a("]: ");
let formatted: FormattedLine[] = lines.map<FormattedText[]>(line => [...prefix, {
text: line,
formats: []
}]);
let formatted = lines.map(line => prefix + line);
let msg: Message = {
date: new Date(),

View File

@ -1,7 +1,8 @@
import { ObservableInterface } from "@hibas123/utils";
import { Colors } from "./index";
import { Adapter, LoggingTypes, Message } from "./types";
import { Adapter, Message, FormattedLine, TerminalFormats, FormatTypes } from "./types";
const browser = typeof window !== "undefined";
export class ConsoleWriter implements Adapter {
init(observable: ObservableInterface<Message>) {
@ -10,10 +11,137 @@ export class ConsoleWriter implements Adapter {
flush() { }
// TODO: Check if required!
// private escape(text: string): string {
// return text
// .replace(/%s/g, "%%s")
// .replace(/%c/g, "%%c")
// }
private formatLine(line: FormattedLine): [string, string[] | undefined] {
let text = "";
let style_formats: string[] = [];
if (!browser) {
for (let part of line) {
let formats = "";
for (let format of part.formats) {
switch (format.type) {
case FormatTypes.BOLD:
formats += TerminalFormats.Bold;
break;
case FormatTypes.UNDERSCORE:
formats += TerminalFormats.Underscore;
break;
case FormatTypes.BLINK:
formats += TerminalFormats.Blink;
break;
case FormatTypes.COLOR:
switch (format.color) {
case Colors.RED:
formats += TerminalFormats.FgRed;
break;
case Colors.GREEN:
formats += TerminalFormats.FgGreen;
break;
case Colors.YELLOW:
formats += TerminalFormats.FgRed;
break;
case Colors.BLUE:
formats += TerminalFormats.FgBlue;
break;
case Colors.MAGENTA:
formats += TerminalFormats.FgMagenta;
break;
case Colors.CYAN:
formats += TerminalFormats.FgCyan;
break;
case Colors.WHITE:
formats += TerminalFormats.FgWhite;
break;
}
break;
}
}
text += formats + part.text + TerminalFormats.Reset;
}
} else {
for (let part of line) {
let styles: string[] = [];
let resetStyles: string[] = [];
for (let format of part.formats) {
switch (format.type) {
case FormatTypes.BOLD:
styles.push("font-weight: bold;");
resetStyles.push("font-weight: unset");
break;
case FormatTypes.UNDERSCORE:
styles.push("text-decoration: underline");
resetStyles.push("text-decoration: unset");
break;
case FormatTypes.BLINK:
styles.push("text-decoration: blink");
resetStyles.push("text-decoration: unset");
break;
case FormatTypes.COLOR:
let color = "";
switch (format.color) {
case Colors.RED:
color = "red";
break;
case Colors.GREEN:
color = "green";
break;
case Colors.YELLOW:
color = "gold";
break;
case Colors.BLUE:
color = "blue";
break;
case Colors.MAGENTA:
color = "magenta";
break;
case Colors.CYAN:
color = "cyan";
break;
case Colors.WHITE:
color = "white";
break;
}
styles.push("color: " + color);
resetStyles.push("color: unset");
break;
}
}
text += "%c" + part.text.replace(/%c/g, "%%c") + "%c";
style_formats.push(styles.join(";"), resetStyles.join(";"));
}
}
return [text, style_formats];
}
onMessage(message: Message) {
let lines = message.text.formatted;
let name = "";
if (message.name) name = `[${message.name}]=>`;
lines.forEach(line => console.log(name + line + Colors.Reset))
let prefix = "";
if (message.name) prefix = `[${message.name}]=>`;
if (browser) {
let text = "";
let formats: string[] = [];
lines.forEach(line => {
let [t, fmts] = this.formatLine(line);
text += t + "\n";
formats.push(...fmts);
})
// console.log(formats);
console.log(text, ...formats);
} else {
lines.forEach(line => {
let [text] = this.formatLine(line);
console.log(prefix + text);
})
}
}
}

View File

@ -1,6 +1,20 @@
import { LoggingBase } from "./base";
export { Colors, LoggingBase, LoggingBaseOptions } from "./base";
export { Adapter, LoggingTypes, Message } from "./types";
export { LoggingBase, LoggingBaseOptions, removeColors } from "./base";
export {
Adapter,
LoggingTypes,
Message,
FormatConfig,
FormattedLine,
DefaultFormatConfig as DefaultColorMap,
FormattedText,
Colors,
Format,
FormatTypes,
TerminalFormats
} from "./types";
export { ObservableInterface } from "@hibas123/utils";
export let Logging: LoggingBase = undefined;

View File

@ -13,6 +13,7 @@ if (typeof err.stack !== "string") console.log("Stacktrace invalid", err.stack)
let cus = new LoggingBase({ name: "test" });
cus.log("Hello from custom Logger")
cus.log("This has some %c symbols inside of it!");
let cus2 = new LoggingBase("test2");
cus2.log("Hello from custom Logger 2")

View File

@ -7,12 +7,103 @@ export enum LoggingTypes {
Debug
}
export const TerminalFormats = {
Reset: "\x1b[0m",
Bold: "\x1b[1m",
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"
}
export enum FormatTypes {
COLOR,
BOLD,
UNDERSCORE,
BLINK
}
export enum Colors {
NONE,
RED,
GREEN,
YELLOW,
BLUE,
MAGENTA,
CYAN,
WHITE
}
export interface FormatConfig {
error: Format[];
warning: Format[];
log: Format[];
debug: Format[];
date: Format[];
file: Format[];
}
function colorFormat(color: Colors) {
return {
type: FormatTypes.COLOR,
color
}
}
const boldFormat = {
type: FormatTypes.BOLD
};
export class DefaultFormatConfig implements FormatConfig {
error = [colorFormat(Colors.RED), boldFormat];
warning = [colorFormat(Colors.YELLOW), boldFormat];
log = [colorFormat(Colors.NONE), boldFormat];
debug = [colorFormat(Colors.CYAN), boldFormat];
date = [colorFormat(Colors.NONE)];
file = [colorFormat(Colors.NONE)];
}
export interface Format {
type: FormatTypes;
color?: Colors;
}
export interface FormattedText {
text: string;
formats: Format[];
}
export type FormattedLine = FormattedText[];
export interface Message {
type: LoggingTypes;
name?: string;
text: {
raw: string[],
formatted: string[]
formatted: FormattedLine[]
};
date: Date;
file: string;