hydrogen-web/src/logging/LogItem.ts

315 lines
10 KiB
TypeScript
Raw Normal View History

2021-11-10 12:06:50 +05:30
/*
Copyright 2020 Bruno Windels <bruno@windels.cloud>
Copyright 2021 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
2021-11-10 18:51:46 +05:30
import {LogLevel, LogFilter} from "./LogFilter";
import type {BaseLogger} from "./BaseLogger";
2021-11-10 12:06:50 +05:30
export interface ISerializedItem {
2021-11-10 19:13:35 +05:30
s: number;
d?: number;
2021-11-10 19:13:35 +05:30
v: LogItemValues;
l: LogLevel;
e?: {
stack?: string;
name: string;
message: string;
};
f?: boolean;
c?: Array<ISerializedItem>;
};
2021-11-15 17:29:08 +05:30
export interface ILogItem {
logger: any;
level: typeof LogLevel;
duration?: number;
end?: number;
2021-11-15 17:29:08 +05:30
start?: number;
logLevel: LogLevel;
children?: Array<ILogItem>;
2021-11-15 17:29:08 +05:30
values: LogItemValues;
error?: Error;
wrap<T>(labelOrValues: LabelOrValues, callback: LogCallback<T>, logLevel?: LogLevel, filterCreator?: FilterCreator): T;
log(labelOrValues: LabelOrValues, logLevel?: LogLevel): void;
2021-11-15 17:29:08 +05:30
set(key: string | object, value: unknown): void;
run<T>(callback: LogCallback<T>): T;
2021-11-15 22:47:38 +05:30
runDetached(labelOrValues: LabelOrValues, callback: LogCallback<unknown>, logLevel?: LogLevel, filterCreator?: FilterCreator): ILogItem;
wrapDetached(labelOrValues: LabelOrValues, callback: LogCallback<unknown>, logLevel?: LogLevel, filterCreator?: FilterCreator): void;
refDetached(logItem: ILogItem, logLevel?: LogLevel): void;
2021-11-15 17:29:08 +05:30
ensureRefId(): void;
catch(err: Error): Error;
finish(): void;
child(labelOrValues: LabelOrValues, logLevel?: LogLevel, filterCreator?: FilterCreator): ILogItem;
2021-11-15 19:32:16 +05:30
serialize(filter: LogFilter, parentStartTime: number | undefined, forced: boolean): ISerializedItem | undefined;
2021-11-15 17:29:08 +05:30
}
2021-11-14 16:24:16 +05:30
export type LogItemValues = {
2021-11-11 15:35:51 +05:30
l?: string;
t?: string;
id?: unknown;
status?: string | number;
refId?: number;
ref?: number;
[key: string]: any
}
2021-11-10 12:06:50 +05:30
export type LabelOrValues = string | LogItemValues;
2021-11-15 18:44:25 +05:30
export type FilterCreator = ((filter: LogFilter, item: ILogItem) => LogFilter);
2021-11-15 22:47:38 +05:30
export type LogCallback<T> = (item: ILogItem) => T;
2021-11-10 12:06:50 +05:30
2021-11-15 17:29:08 +05:30
export class LogItem implements ILogItem {
2021-11-10 19:07:24 +05:30
public readonly start: number;
2021-11-10 12:06:50 +05:30
public logLevel: LogLevel;
public error?: Error;
public end?: number;
2021-11-10 12:06:50 +05:30
private _values: LogItemValues;
private _logger: BaseLogger;
2021-11-15 18:44:25 +05:30
private _filterCreator?: FilterCreator;
private _children?: Array<LogItem>;
2021-11-10 12:06:50 +05:30
2021-11-15 18:44:25 +05:30
constructor(labelOrValues: LabelOrValues, logLevel: LogLevel, logger: BaseLogger, filterCreator?: FilterCreator) {
2021-11-10 12:06:50 +05:30
this._logger = logger;
this.start = logger._now();
// (l)abel
this._values = typeof labelOrValues === "string" ? {l: labelOrValues} : labelOrValues;
this.logLevel = logLevel;
this._filterCreator = filterCreator;
}
/** start a new root log item and run it detached mode, see BaseLogger.runDetached */
2021-11-15 22:47:38 +05:30
runDetached(labelOrValues: LabelOrValues, callback: LogCallback<unknown>, logLevel?: LogLevel, filterCreator?: FilterCreator): ILogItem {
2021-11-10 12:06:50 +05:30
return this._logger.runDetached(labelOrValues, callback, logLevel, filterCreator);
}
/** start a new detached root log item and log a reference to it from this item */
2021-11-15 22:47:38 +05:30
wrapDetached(labelOrValues: LabelOrValues, callback: LogCallback<unknown>, logLevel?: LogLevel, filterCreator?: FilterCreator): void {
2021-11-10 12:06:50 +05:30
this.refDetached(this.runDetached(labelOrValues, callback, logLevel, filterCreator));
}
/** logs a reference to a different log item, usually obtained from runDetached.
This is useful if the referenced operation can't be awaited. */
refDetached(logItem: ILogItem, logLevel?: LogLevel): void {
2021-11-10 12:06:50 +05:30
logItem.ensureRefId();
2021-11-15 17:29:08 +05:30
this.log({ref: (logItem as LogItem)._values.refId}, logLevel);
2021-11-10 12:06:50 +05:30
}
2021-11-14 15:55:42 +05:30
ensureRefId(): void {
2021-11-10 12:06:50 +05:30
if (!this._values.refId) {
this.set("refId", this._logger._createRefId());
}
}
/**
* Creates a new child item and runs it in `callback`.
*/
wrap<T>(labelOrValues: LabelOrValues, callback: LogCallback<T>, logLevel?: LogLevel, filterCreator?: FilterCreator): T {
2021-11-10 12:06:50 +05:30
const item = this.child(labelOrValues, logLevel, filterCreator);
return item.run(callback);
}
2021-11-17 11:40:38 +05:30
get duration(): number | undefined {
2021-11-10 12:06:50 +05:30
if (this.end) {
return this.end - this.start;
} else {
return undefined;
2021-11-10 12:06:50 +05:30
}
}
2021-11-17 11:40:38 +05:30
durationWithoutType(type: string): number | undefined {
const durationOfType = this.durationOfType(type);
if (this.duration && durationOfType) {
return this.duration - durationOfType;
2021-11-10 12:17:43 +05:30
}
2021-11-10 12:06:50 +05:30
}
durationOfType(type: string): number | undefined {
2021-11-10 12:06:50 +05:30
if (this._values.t === type) {
return this.duration;
} else if (this._children) {
return this._children.reduce((sum, c) => {
const duration = c.durationOfType(type);
2021-11-16 13:08:13 +05:30
return sum + (duration ?? 0);
2021-11-10 12:06:50 +05:30
}, 0);
} else {
return 0;
}
}
/**
* Creates a new child item that finishes immediately
* and can hence not be modified anymore.
*
* Hence, the child item is not returned.
*/
log(labelOrValues: LabelOrValues, logLevel?: LogLevel): void {
2021-11-15 18:44:25 +05:30
const item = this.child(labelOrValues, logLevel);
2021-11-10 12:06:50 +05:30
item.end = item.start;
}
set(key: string | object, value?: unknown): void {
2021-11-10 12:06:50 +05:30
if(typeof key === "object") {
const values = key;
Object.assign(this._values, values);
} else {
this._values[key] = value;
}
}
2021-11-14 15:55:42 +05:30
// todo: null or undefined here?
2021-11-15 19:32:16 +05:30
serialize(filter: LogFilter, parentStartTime: number | undefined, forced: boolean): ISerializedItem | undefined {
2021-11-10 12:06:50 +05:30
if (this._filterCreator) {
try {
filter = this._filterCreator(new LogFilter(filter), this);
} catch (err) {
console.error("Error creating log filter", err);
}
}
2021-11-10 19:13:35 +05:30
let children: Array<ISerializedItem> | null = null;
if (this._children) {
2021-11-10 19:13:35 +05:30
children = this._children.reduce((array: Array<ISerializedItem>, c) => {
2021-11-10 12:06:50 +05:30
const s = c.serialize(filter, this.start, false);
if (s) {
if (array === null) {
array = [];
}
array.push(s);
}
return array;
}, null);
}
if (filter && !filter.filter(this, children)) {
2021-11-15 19:32:16 +05:30
return;
2021-11-10 12:06:50 +05:30
}
// in (v)alues, (l)abel and (t)ype are also reserved.
2021-11-10 19:13:35 +05:30
const item: ISerializedItem = {
2021-11-10 12:06:50 +05:30
// (s)tart
2021-11-15 19:32:16 +05:30
s: parentStartTime? this.start - parentStartTime : this.start,
2021-11-10 12:06:50 +05:30
// (d)uration
d: this.duration,
// (v)alues
v: this._values,
// (l)evel
l: this.logLevel
};
2021-11-12 15:06:11 +05:30
if (this.error) {
2021-11-10 12:06:50 +05:30
// (e)rror
item.e = {
2021-11-12 15:06:11 +05:30
stack: this.error.stack,
name: this.error.name,
message: this.error.message.split("\n")[0]
2021-11-10 12:06:50 +05:30
};
}
if (forced) {
item.f = true; //(f)orced
}
if (children) {
// (c)hildren
item.c = children;
}
return item;
}
/**
* You probably want to use `wrap` instead of this.
*
* Runs a callback passing this log item,
* recording the timing and any error.
*
* callback can return a Promise.
*
* Should only be called once.
*
* @param {Function} callback [description]
* @return {[type]} [description]
*/
run<T>(callback: LogCallback<T>): T {
if (this.end) {
2021-11-10 12:06:50 +05:30
console.trace("log item is finished, additional logs will likely not be recorded");
}
2021-11-15 22:47:38 +05:30
let result: T | Promise<T>;
2021-11-10 12:06:50 +05:30
try {
result = callback(this);
if (result instanceof Promise) {
return result.then(promiseResult => {
this.finish();
return promiseResult;
}, err => {
throw this.catch(err);
}) as unknown as T;
2021-11-10 12:06:50 +05:30
} else {
this.finish();
return result;
}
} catch (err) {
throw this.catch(err);
}
}
/**
* finished the item, recording the end time. After finishing, an item can't be modified anymore as it will be persisted.
* @internal shouldn't typically be called by hand. allows to force finish if a promise is still running when closing the app
*/
2021-11-14 15:55:42 +05:30
finish(): void {
if (!this.end) {
if (this._children) {
2021-11-10 12:06:50 +05:30
for(const c of this._children) {
c.finish();
}
}
this.end = this._logger._now();
}
}
// expose log level without needing import everywhere
get level(): typeof LogLevel {
2021-11-10 12:06:50 +05:30
return LogLevel;
}
catch(err: Error): Error {
2021-11-12 15:06:11 +05:30
this.error = err;
2021-11-10 12:06:50 +05:30
this.logLevel = LogLevel.Error;
this.finish();
return err;
}
child(labelOrValues: LabelOrValues, logLevel?: LogLevel, filterCreator?: FilterCreator): ILogItem {
if (this.end) {
2021-11-10 12:06:50 +05:30
console.trace("log item is finished, additional logs will likely not be recorded");
}
if (!logLevel) {
logLevel = this.logLevel || LogLevel.Info;
}
2021-11-15 18:44:25 +05:30
const item = new LogItem(labelOrValues, logLevel, this._logger, filterCreator);
if (!this._children) {
2021-11-10 12:06:50 +05:30
this._children = [];
}
this._children.push(item);
return item;
}
2021-11-14 15:55:42 +05:30
get logger(): BaseLogger {
2021-11-10 12:06:50 +05:30
return this._logger;
}
2021-11-14 16:24:16 +05:30
get values(): LogItemValues {
return this._values;
}
get children(): Array<LogItem> | undefined {
2021-11-14 16:24:16 +05:30
return this._children;
}
2021-11-10 12:06:50 +05:30
}