Compare commits

..

9 Commits

Author SHA1 Message Date
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 5982 additions and 85 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",
"version": "3.0.3",
"version": "3.1.2",
"description": "",
"author": "Fabian Stamm <dev@fabianstamm.de>",
"contributors": [],

5839
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -6,28 +6,13 @@ import {
Format,
FormatConfig,
Formatted,
ILoggingInterface,
LoggingTypes,
Message,
} from "./types.js";
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 {
/**
* Name will be prefixed on Console output and added to logfiles, if not specified here
@ -89,6 +74,12 @@ export abstract class LoggingInterface implements ILoggingInterface {
constructor(names: string[]) {
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[]) {
@ -179,7 +170,10 @@ export class LoggingBase extends LoggingInterface {
}
getChild(name: string) {
return new LoggingBase.DecoupledLogging([this.names, name], this.#lg);
return new LoggingBase.DecoupledLogging(
[...this.names, name],
this.#lg
);
}
};
@ -208,12 +202,6 @@ export class LoggingBase extends LoggingInterface {
if (options.console) {
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) {
@ -234,7 +222,7 @@ export class LoggingBase extends LoggingInterface {
if (!init) {
add();
} else {
Promise.resolve(init).then(add);
await Promise.resolve(init).then(add);
}
}
@ -255,7 +243,8 @@ export class LoggingBase extends LoggingInterface {
}
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;
if (this.#resolve_filename) {
@ -331,23 +320,14 @@ export class LoggingBase extends LoggingInterface {
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];
message.forEach((msg, idx) => {
let format = new Formatted();
let format: Formatted;
if (msg instanceof Formatted) {
format = msg;
msg = msg.content;
} else {
format = new Formatted();
}
if (typeof msg !== "string") {
@ -358,18 +338,17 @@ export class LoggingBase extends LoggingInterface {
}) as string;
}
removeColors(msg)
.split("\n")
.forEach((text, index, { length }) => {
if (index != length - 1) {
formattedMessage.push(
new Formatted(text + "\n", format),
...linePrefix
);
} else {
formattedMessage.push(new Formatted(text, format));
}
});
// removeColors(msg) // Remove colors is uncommented for now, since there are no real benefits of having it and it reduces performance
msg.split("\n").forEach((text, index, { length }) => {
if (index != length - 1) {
formattedMessage.push(
new Formatted(text + "\n", format),
...linePrefix
);
} else {
formattedMessage.push(new Formatted(text, format));
}
});
formattedMessage.push(new Formatted(" "));
});
@ -381,26 +360,30 @@ export class LoggingBase extends LoggingInterface {
type,
};
this.#adapters.forEach((adapter) => adapter.onMessage(msg));
this.#adapters.forEach((adapter) => {
if (adapter.level <= type) {
adapter.onMessage(msg);
}
});
}
async close() {
if (this.#closed) return;
this.#closed = true;
this.#adapters.forEach((adapter) => {
for (const adapter of this.#adapters) {
const cnt = LoggingBase[InitialisedAdapters].get(adapter);
if (!cnt) {
//TODO: should not happen!
} else {
if (cnt <= 1) {
adapter.close();
if (adapter.close) await adapter.close();
LoggingBase[InitialisedAdapters].delete(adapter);
} else {
LoggingBase[InitialisedAdapters].set(adapter, cnt - 1);
}
}
});
}
}
}
@ -446,9 +429,11 @@ function getCallerFile() {
return { file: undefined, line: 0 };
}
function getCallerFromExisting(
err: Error
): { file: string; line: number; column?: number } {
function getCallerFromExisting(err: Error): {
file: string;
line: number;
column?: number;
} {
if (!err || !err.stack) return { file: "NOFILE", line: 0 };
let lines = err.stack.split("\n");
lines.shift(); // removing first line
@ -479,6 +464,7 @@ function getCallerFromExisting(
export function removeColors(text: string) {
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,
""
);

View File

@ -5,6 +5,7 @@ import {
TerminalFormats,
Formatted,
IFormatted,
LoggingTypes,
} from "./types.js";
declare const Deno: any;
@ -15,11 +16,15 @@ const deno = typeof Deno !== "undefined";
const NodeJS = typeof process !== undefined;
export class ConsoleAdapter implements Adapter {
level: LoggingTypes = LoggingTypes.Debug;
constructor(private colors: boolean = true) {}
init() {}
flush() {}
setLevel(level: LoggingTypes) {
this.level = level;
}
// TODO: Check if required!
// private escape(text: string): string {
// return text

View File

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

View File

@ -203,7 +203,7 @@ export class DefaultFormatConfig implements FormatConfig {
date = 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();
}
@ -216,6 +216,8 @@ export interface Message {
}
export interface Adapter {
readonly level: LoggingTypes;
/**
* This function initialises the Adapter. It might be called multiple times, when added to multiple instances
* @param observable An observable to subscribe to messages
@ -225,6 +227,8 @@ export interface Adapter {
flush(sync: true): void;
flush(sync: false): void | Promise<void>;
setLevel(level: LoggingTypes): void;
onMessage(message: Message): void;
/**
@ -234,3 +238,19 @@ export interface Adapter {
*/
close?(): void;
}
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;
}

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": {
"module": "commonjs",
"target": "esnext",
"module": "ESNext",
"target": "ESNext",
"moduleResolution": "node",
"outDir": "esm",
"noImplicitAny": false,
"sourceMap": true,
"outDir": "out",
"declaration": true,
"typeRoots": ["node_modules/@types"]
"declaration": true
},
"exclude": ["node_modules"],
"include": ["src"]