Fixing some problems with the adapter API

This commit is contained in:
Fabian Stamm 2020-04-09 18:00:59 +02:00
parent 94d9731cdd
commit 9182efe7e7
3 changed files with 41 additions and 9 deletions

View File

@ -1,6 +1,6 @@
{
"name": "@hibas123/logging",
"version": "2.2.2",
"version": "2.3.0",
"description": "",
"main": "out/index.js",
"types": "out/index.d.ts",

View File

@ -42,6 +42,7 @@ export interface LoggingBaseOptions {
console: boolean;
}
const adapterCache = new WeakMap<Adapter, number>();
export class LoggingBase {
private _formatMap: FormatConfig = new DefaultFormatConfig();
@ -110,8 +111,12 @@ export class LoggingBase {
addAdapter(adapter: Adapter) {
if (!this.adapter.has(adapter)) {
this.adapter.add(adapter);
let cached = adapterCache.get(adapter) || 0;
adapterCache.set(adapter, cached + 1);
let prms = Promise.resolve(
adapter.init(this.messageObservable.getPublicApi(), this._name)
adapter.init(this.messageObservable.getPublicApi())
);
this.adapter_init.push(prms);
}
@ -129,10 +134,29 @@ export class LoggingBase {
}
}
private $closed = false;
public close() {
this.adapter.forEach((adapter) =>
adapter.close ? adapter.close() : undefined
);
if (this.$closed) return;
this.$closed = true;
this.adapter.forEach((adapter) => {
let cached = adapterCache.get(adapter);
if (cached) {
cached--;
if (cached <= 0) {
adapterCache.delete(adapter);
adapter.close();
} else adapterCache.set(adapter, cached);
}
adapter.close ? adapter.close() : undefined;
});
this.adapter = undefined;
this.messageObservable.close();
}
public waitForSetup() {
@ -234,6 +258,8 @@ export class LoggingBase {
message: any[],
caller?: { file: string; line: number }
) {
if (this.$closed) return;
let date = new Date().toISOString().replace(/T/, " ").replace(/\..+/, "");
let file_raw = caller || getCallerFile();

View File

@ -107,13 +107,19 @@ export interface Message {
}
export interface Adapter {
init(
observable: ObservableInterface<Message>,
name?: string
): void | Promise<void>;
/**
* This function initialises the Adapter. It might be called multiple times, when added to multiple instances
* @param observable An observable to subscribe to messages
*/
init(observable: ObservableInterface<Message>): void | Promise<void>;
flush(sync: true): void;
flush(sync: false): void | Promise<void>;
/**
* When a close function is available, it will be called when no logging instance references it anymore.
*
* WARNING: The adapter might be reinitialised, when it is added to a new Logging instance
*/
close?(): void;
}