Compare commits

..

10 Commits

Author SHA1 Message Date
3526766e68 Add more time functions 2025-10-21 13:59:24 +02:00
3de5f368ef Add typescript declarations 2023-11-22 22:27:54 +01:00
e0b51625d8 Make it ESM only 2023-11-22 22:18:40 +01:00
153aca0ccb Add missing await to addAdapter init 2021-05-19 11:41:14 +02:00
7ca0c4fd72 Some performance optimizations 2021-05-18 14:10:59 +02:00
8e183ac1a5 Add adapter based control of log level 2021-05-18 09:10:06 +02:00
feed4626e6 Fix bugf 2021-05-09 22:33:47 +02:00
9d4e521619 Fix error with non existing close on adapter 2021-05-08 22:53:12 +02:00
7d75f65dd3 Bind functions of Logging to this 2021-05-08 22:28:06 +02:00
eeed068ddd Add exports 2021-05-08 22:24:00 +02:00
10 changed files with 4586 additions and 112 deletions

54
benchmark.js Normal file
View File

@ -0,0 +1,54 @@
const { LoggingBase } = require("./out/index.js");
let results = {};
function benchmark(name, count, runner) {
console.profile(name);
const start = process.hrtime.bigint()
runner(count);
const diffNS = process.hrtime.bigint() - start;
const diffMS = Number(diffNS / 1000n / 1000n);
console.profileEnd(name)
results[name]= {
count,
time: diffMS,
timePerI: (diffMS / count).toFixed(4)
}
}
benchmark("simple", 10000000, (cnt) => {
const l = new LoggingBase({
console: false
});
for (let i = 0; i < cnt; i++) {
l.log("simple log")
}
})
benchmark("complex", 1000000, (cnt) => {
const l = new LoggingBase({
console: false
});
for (let i = 0; i < cnt; i++) {
l.log("complex log", {
a: 1,
b: {
c:"test"
}
})
}
})
benchmark("very long", 10000000, (cnt) => {
const l = new LoggingBase({
console: false
});
const longText = "complex log".repeat(100);
for (let i = 0; i < cnt; i++) {
l.log(longText)
}
})
console.table(results)

View File

@ -1,6 +1,6 @@
{ {
"name": "logging", "name": "logging",
"version": "3.0.3", "version": "3.1.2",
"description": "", "description": "",
"author": "Fabian Stamm <dev@fabianstamm.de>", "author": "Fabian Stamm <dev@fabianstamm.de>",
"contributors": [], "contributors": [],

4386
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,15 +1,17 @@
{ {
"name": "@hibas123/logging", "name": "@hibas123/logging",
"version": "3.0.3", "version": "4.0.2",
"description": "", "description": "",
"main": "out/index.js", "type": "module",
"types": "out/index.d.ts", "main": "esm/index.js",
"types": "esm/index.d.ts",
"module": "esm/index.js", "module": "esm/index.js",
"scripts": { "scripts": {
"prepublish": "npm run build", "prepublishOnly": "npm run build",
"build": "tsc && tsc -p tsconfig.esm.json", "build": "tsc",
"test": "tsc && node out/test.js", "test": "tsc && node esm/test.js",
"postpublish": "denreg publish" "bench": "tsc && node benchmark.js",
"prof": "tsc && ndb --prof benchmark.js"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@ -19,16 +21,15 @@
"license": "MIT", "license": "MIT",
"files": [ "files": [
"src/", "src/",
"out/",
"esm/", "esm/",
"tsconfig.json", "tsconfig.json",
"readme.md" "readme.md"
], ],
"devDependencies": { "devDependencies": {
"concurrently": "^6.0.2", "concurrently": "^9.2.1",
"nodemon": "^2.0.7", "ndb": "^1.1.5",
"ts-node": "^9.1.1", "nodemon": "^3.1.10",
"typescript": "^4.2.4" "ts-node": "^10.9.2",
}, "typescript": "^5.9.3"
"dependencies": {} }
} }

View File

@ -6,28 +6,13 @@ import {
Format, Format,
FormatConfig, FormatConfig,
Formatted, Formatted,
ILoggingInterface,
LoggingTypes, LoggingTypes,
Message, Message,
} from "./types.js"; } from "./types.js";
const browser = typeof window !== "undefined"; const browser = typeof window !== "undefined";
export interface ILoggingTimer {
end: () => number;
}
export interface ILoggingInterface {
debug(...message: any[]): void;
log(...message: any[]): void;
warn(...message: any[]): void;
error(...message: any[]): void;
time(name?: string): ILoggingTimer;
timeEnd(id: string): number;
getChild(name: string): ILoggingInterface;
}
export interface ILoggingOptions { export interface ILoggingOptions {
/** /**
* Name will be prefixed on Console output and added to logfiles, if not specified here * Name will be prefixed on Console output and added to logfiles, if not specified here
@ -46,6 +31,7 @@ export interface ILoggingOptions {
export interface INativeFunctions { export interface INativeFunctions {
startTimer(): any; startTimer(): any;
diffTime(start: any, end: any): number;
endTimer(start: any): number; endTimer(start: any): number;
} }
@ -57,6 +43,9 @@ export const DefaultNativeFunctions = {
return Date.now(); return Date.now();
} }
}, },
diffTime: (start: any, end: any) => {
return end - start;
},
endTimer: (start: any) => { endTimer: (start: any) => {
if (browser && window.performance && window.performance.now) { if (browser && window.performance && window.performance.now) {
return window.performance.now() - start; return window.performance.now() - start;
@ -74,7 +63,7 @@ const InitialisedAdapters = Symbol("@hibas123/logging:initialisedAdapters");
export abstract class LoggingInterface implements ILoggingInterface { export abstract class LoggingInterface implements ILoggingInterface {
#names: string[]; #names: string[];
#timerMap = new Map<string, { name: string; start: any }>(); #timerMap = new Map<string, { name: string; start: any, marks: { time: any, name: string }[] }>();
get names() { get names() {
return [...this.#names]; return [...this.#names];
@ -89,6 +78,12 @@ export abstract class LoggingInterface implements ILoggingInterface {
constructor(names: string[]) { constructor(names: string[]) {
this.#names = names; this.#names = names;
for (const key in this) {
if (typeof this[key] === "function") {
this[key] = (this[key] as never as Function).bind(this);
}
}
} }
debug(...message: any[]) { debug(...message: any[]) {
@ -132,13 +127,18 @@ export abstract class LoggingInterface implements ILoggingInterface {
time(id?: string) { time(id?: string) {
if (!id) id = Math.floor(Math.random() * 899999 + 100000).toString(); if (!id) id = Math.floor(Math.random() * 899999 + 100000).toString();
this.#timerMap.set(id, { let timer = {
name: id, name: id,
start: LoggingBase.nativeFunctions.startTimer(), start: LoggingBase.nativeFunctions.startTimer(),
}); marks: [],
};
this.#timerMap.set(id, timer);
return { return {
id, id,
mark: (label: string) => {
timer.marks.push({ time: LoggingBase.nativeFunctions.startTimer(), name: label });
},
end: () => this.timeEnd(id), end: () => this.timeEnd(id),
}; };
} }
@ -146,7 +146,8 @@ export abstract class LoggingInterface implements ILoggingInterface {
timeEnd(id: string) { timeEnd(id: string) {
let timer = this.#timerMap.get(id); let timer = this.#timerMap.get(id);
if (timer) { if (timer) {
let diff = LoggingBase.nativeFunctions.endTimer(timer.start); let end_time = LoggingBase.nativeFunctions.startTimer();
let diff = LoggingBase.nativeFunctions.diffTime(timer.start, end_time);
this.message(LoggingTypes.Debug, this.#names, [ this.message(LoggingTypes.Debug, this.#names, [
Format.green(`[${timer.name}]`), Format.green(`[${timer.name}]`),
@ -155,6 +156,27 @@ export abstract class LoggingInterface implements ILoggingInterface {
"ms", "ms",
]); ]);
if (timer.marks.length > 0) {
let last_mark = timer.start;
for (let mark of timer.marks) {
let diff = LoggingBase.nativeFunctions.diffTime(last_mark, mark.time);
this.message(LoggingTypes.Debug, [...this.#names, timer.name], [
Format.green(`[${mark.name}]`),
`->`,
Format.blue(diff.toFixed(4)),
"ms",
]);
last_mark = mark.time;
}
let diff = LoggingBase.nativeFunctions.diffTime(last_mark, end_time);
this.message(LoggingTypes.Debug, [...this.#names, timer.name], [
Format.green(`[end]`),
`->`,
Format.blue(diff.toFixed(4)),
"ms",
]);
}
return diff; return diff;
} }
return -1; return -1;
@ -179,7 +201,10 @@ export class LoggingBase extends LoggingInterface {
} }
getChild(name: string) { getChild(name: string) {
return new LoggingBase.DecoupledLogging([this.names, name], this.#lg); return new LoggingBase.DecoupledLogging(
[...this.names, name],
this.#lg
);
} }
}; };
@ -208,12 +233,6 @@ export class LoggingBase extends LoggingInterface {
if (options.console) { if (options.console) {
this.addAdapter(consoleAdapter); this.addAdapter(consoleAdapter);
} }
for (const key in this) {
if (typeof this[key] === "function") {
this[key] = ((this[key] as never) as Function).bind(this);
}
}
} }
async addAdapter(adapter: Adapter) { async addAdapter(adapter: Adapter) {
@ -234,7 +253,7 @@ export class LoggingBase extends LoggingInterface {
if (!init) { if (!init) {
add(); add();
} else { } else {
Promise.resolve(init).then(add); await Promise.resolve(init).then(add);
} }
} }
@ -255,7 +274,8 @@ export class LoggingBase extends LoggingInterface {
} }
const date = new Date(); const date = new Date();
const date_str = date.toISOString().replace(/T/, " ").replace(/\..+/, ""); const isoStr = date.toISOString();
const date_str = isoStr.substring(0, 10) + " " + isoStr.substring(11, 19);
let file: string | undefined = undefined; let file: string | undefined = undefined;
if (this.#resolve_filename) { if (this.#resolve_filename) {
@ -284,9 +304,8 @@ export class LoggingBase extends LoggingInterface {
file_raw.file = newF; file_raw.file = newF;
} }
file = `${file_raw.file || "<unknown>"}:${file_raw.line}:${ file = `${file_raw.file || "<unknown>"}:${file_raw.line}:${file_raw.column || 0
file_raw.column || 0 }`;
}`;
} }
let type_str = LoggingTypes[type].toUpperCase().padEnd(5, " "); let type_str = LoggingTypes[type].toUpperCase().padEnd(5, " ");
@ -331,23 +350,14 @@ export class LoggingBase extends LoggingInterface {
new Formatted(": "), new Formatted(": "),
]; ];
// let linePrefix = [
// ...namePrefix,
// new Formatted(date_str, this.#format_map.date),
// new Formatted(" "),
// new Formatted(type_str, type_format),
// ...(file
// ? [new Formatted(" "), new Formatted(file, this.#format_map.file)]
// : []),
// new Formatted("| "),
// ];
let formattedMessage: Formatted<string>[] = [...linePrefix]; let formattedMessage: Formatted<string>[] = [...linePrefix];
message.forEach((msg, idx) => { message.forEach((msg, idx) => {
let format = new Formatted(); let format: Formatted;
if (msg instanceof Formatted) { if (msg instanceof Formatted) {
format = msg; format = msg;
msg = msg.content; msg = msg.content;
} else {
format = new Formatted();
} }
if (typeof msg !== "string") { if (typeof msg !== "string") {
@ -358,18 +368,17 @@ export class LoggingBase extends LoggingInterface {
}) as string; }) as string;
} }
removeColors(msg) // removeColors(msg) // Remove colors is uncommented for now, since there are no real benefits of having it and it reduces performance
.split("\n") msg.split("\n").forEach((text, index, { length }) => {
.forEach((text, index, { length }) => { if (index != length - 1) {
if (index != length - 1) { formattedMessage.push(
formattedMessage.push( new Formatted(text + "\n", format),
new Formatted(text + "\n", format), ...linePrefix
...linePrefix );
); } else {
} else { formattedMessage.push(new Formatted(text, format));
formattedMessage.push(new Formatted(text, format)); }
} });
});
formattedMessage.push(new Formatted(" ")); formattedMessage.push(new Formatted(" "));
}); });
@ -381,26 +390,30 @@ export class LoggingBase extends LoggingInterface {
type, type,
}; };
this.#adapters.forEach((adapter) => adapter.onMessage(msg)); this.#adapters.forEach((adapter) => {
if (adapter.level <= type) {
adapter.onMessage(msg);
}
});
} }
async close() { async close() {
if (this.#closed) return; if (this.#closed) return;
this.#closed = true; this.#closed = true;
this.#adapters.forEach((adapter) => { for (const adapter of this.#adapters) {
const cnt = LoggingBase[InitialisedAdapters].get(adapter); const cnt = LoggingBase[InitialisedAdapters].get(adapter);
if (!cnt) { if (!cnt) {
//TODO: should not happen! //TODO: should not happen!
} else { } else {
if (cnt <= 1) { if (cnt <= 1) {
adapter.close(); if (adapter.close) await adapter.close();
LoggingBase[InitialisedAdapters].delete(adapter); LoggingBase[InitialisedAdapters].delete(adapter);
} else { } else {
LoggingBase[InitialisedAdapters].set(adapter, cnt - 1); LoggingBase[InitialisedAdapters].set(adapter, cnt - 1);
} }
} }
}); }
} }
} }
@ -442,13 +455,15 @@ function getCallerFile() {
}; };
} }
} }
} catch (err) {} } catch (err) { }
return { file: undefined, line: 0 }; return { file: undefined, line: 0 };
} }
function getCallerFromExisting( function getCallerFromExisting(err: Error): {
err: Error file: string;
): { file: string; line: number; column?: number } { line: number;
column?: number;
} {
if (!err || !err.stack) return { file: "NOFILE", line: 0 }; if (!err || !err.stack) return { file: "NOFILE", line: 0 };
let lines = err.stack.split("\n"); let lines = err.stack.split("\n");
lines.shift(); // removing first line lines.shift(); // removing first line
@ -479,6 +494,7 @@ function getCallerFromExisting(
export function removeColors(text: string) { export function removeColors(text: string) {
text = text.replace( text = text.replace(
// Putting regex here directly instead of externally actually improves performance. The cause of that is not clear for now.
/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
"" ""
); );

View File

@ -5,6 +5,7 @@ import {
TerminalFormats, TerminalFormats,
Formatted, Formatted,
IFormatted, IFormatted,
LoggingTypes,
} from "./types.js"; } from "./types.js";
declare const Deno: any; declare const Deno: any;
@ -15,11 +16,15 @@ const deno = typeof Deno !== "undefined";
const NodeJS = typeof process !== undefined; const NodeJS = typeof process !== undefined;
export class ConsoleAdapter implements Adapter { export class ConsoleAdapter implements Adapter {
constructor(private colors: boolean = true) {} level: LoggingTypes = LoggingTypes.Debug;
constructor(private colors: boolean = true) { }
init() {} init() { }
flush() {} flush() { }
setLevel(level: LoggingTypes) {
this.level = level;
}
// TODO: Check if required! // TODO: Check if required!
// private escape(text: string): string { // private escape(text: string): string {
// return text // return text
@ -127,22 +132,22 @@ export class ConsoleAdapter implements Adapter {
let color = ""; let color = "";
switch (format.color) { switch (format.color) {
case Colors.RED: case Colors.RED:
color = "red"; color = "#ff5f5f";
break; break;
case Colors.GREEN: case Colors.GREEN:
color = "green"; color = "#62ff5f";
break; break;
case Colors.YELLOW: case Colors.YELLOW:
color = "gold"; color = "#ffea37";
break; break;
case Colors.BLUE: case Colors.BLUE:
color = "blue"; color = "#379aff";
break; break;
case Colors.MAGENTA: case Colors.MAGENTA:
color = "magenta"; color = "#f837ff";
break; break;
case Colors.CYAN: case Colors.CYAN:
color = "cyan"; color = "#37e4ff";
break; break;
case Colors.WHITE: case Colors.WHITE:
color = "white"; color = "white";
@ -156,22 +161,22 @@ export class ConsoleAdapter implements Adapter {
let color = ""; let color = "";
switch (format.bgcolor) { switch (format.bgcolor) {
case Colors.RED: case Colors.RED:
color = "red"; color = "#ff5f5f";
break; break;
case Colors.GREEN: case Colors.GREEN:
color = "green"; color = "#62ff5f";
break; break;
case Colors.YELLOW: case Colors.YELLOW:
color = "gold"; color = "#ffea37";
break; break;
case Colors.BLUE: case Colors.BLUE:
color = "blue"; color = "#379aff";
break; break;
case Colors.MAGENTA: case Colors.MAGENTA:
color = "magenta"; color = "#f837ff";
break; break;
case Colors.CYAN: case Colors.CYAN:
color = "cyan"; color = "#37e4ff";
break; break;
case Colors.WHITE: case Colors.WHITE:
color = "white"; color = "white";

View File

@ -14,6 +14,8 @@ export {
TerminalFormats, TerminalFormats,
Formatted, Formatted,
IFormatted, IFormatted,
ILoggingInterface,
ILoggingTimer,
} from "./types.js"; } from "./types.js";
const Logging = new LoggingBase(); const Logging = new LoggingBase();

View File

@ -203,7 +203,7 @@ export class DefaultFormatConfig implements FormatConfig {
date = new Formatted()._color(IColors.NONE); date = new Formatted()._color(IColors.NONE);
file = new Formatted()._color(IColors.NONE); file = new Formatted()._color(IColors.NONE);
names = new Formatted()._bold()._color(IColors.GREEN); names = new Formatted()._bold()._color(IColors.CYAN);
names_delimiter = new Formatted(" -> ")._bold(); names_delimiter = new Formatted(" -> ")._bold();
} }
@ -216,6 +216,8 @@ export interface Message {
} }
export interface Adapter { export interface Adapter {
readonly level: LoggingTypes;
/** /**
* This function initialises the Adapter. It might be called multiple times, when added to multiple instances * This function initialises the Adapter. It might be called multiple times, when added to multiple instances
* @param observable An observable to subscribe to messages * @param observable An observable to subscribe to messages
@ -225,6 +227,8 @@ export interface Adapter {
flush(sync: true): void; flush(sync: true): void;
flush(sync: false): void | Promise<void>; flush(sync: false): void | Promise<void>;
setLevel(level: LoggingTypes): void;
onMessage(message: Message): void; onMessage(message: Message): void;
/** /**
@ -234,3 +238,20 @@ export interface Adapter {
*/ */
close?(): void; close?(): void;
} }
export interface ILoggingTimer {
mark: (label: string) => void;
end: () => number;
}
export interface ILoggingInterface {
debug(...message: any[]): void;
log(...message: any[]): void;
warn(...message: any[]): void;
error(...message: any[]): void;
time(name?: string): ILoggingTimer;
timeEnd(id: string): number;
getChild(name: string): ILoggingInterface;
}

View File

@ -1,11 +0,0 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "ESNext",
"target": "ES2017",
"moduleResolution": "node",
"outDir": "esm"
},
"exclude": ["node_modules"],
"include": ["src"]
}

View File

@ -1,12 +1,12 @@
{ {
"compilerOptions": { "compilerOptions": {
"module": "commonjs", "module": "ESNext",
"target": "esnext", "target": "ESNext",
"moduleResolution": "node",
"outDir": "esm",
"noImplicitAny": false, "noImplicitAny": false,
"sourceMap": true, "sourceMap": true,
"outDir": "out", "declaration": true
"declaration": true,
"typeRoots": ["node_modules/@types"]
}, },
"exclude": ["node_modules"], "exclude": ["node_modules"],
"include": ["src"] "include": ["src"]