refactor: make console log less verbose when not needed

This commit is contained in:
鲁树人
2023-05-22 00:00:35 +01:00
parent 63fff9be3a
commit bb633cd6f2
6 changed files with 52 additions and 23 deletions

View File

@@ -2,21 +2,19 @@ function isPromise<T = unknown>(p: unknown): p is Promise<T> {
return !!p && typeof p === 'object' && 'then' in p && 'catch' in p && 'finally' in p;
}
export function timedLogger<R = unknown>(label: string, fn: () => R): R {
console.time(label);
export function wrapFunctionCall<R = unknown>(pre: () => void, post: () => void, fn: () => R): R {
pre();
try {
const result = fn();
if (isPromise(result)) {
result.finally(() => {
console.timeEnd(label);
});
result.finally(post);
}
return result;
} catch (e) {
console.timeEnd(label);
post();
throw e;
}
}

25
src/util/logUtils.ts Normal file
View File

@@ -0,0 +1,25 @@
import { wrapFunctionCall } from './fnWrapper';
export function timedLogger<R = unknown>(label: string, fn: () => R): R {
if (import.meta.env.ENABLE_PERF_LOG !== '1') {
return fn();
} else {
return wrapFunctionCall(
() => console.time(label),
() => console.timeEnd(label),
fn
);
}
}
export function withGroupedLogs<R = unknown>(label: string, fn: () => R): R {
if (import.meta.env.ENABLE_PERF_LOG !== '1') {
return fn();
} else {
return wrapFunctionCall(
() => console.group(label),
() => (console.groupEnd as (label: string) => void)(label),
() => timedLogger(`${label}/total`, fn)
);
}
}