mirror of
https://git.um-react.app/um/um-react.git
synced 2025-11-28 11:33:02 +00:00
refactor: make console log less verbose when not needed
This commit is contained in:
@@ -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
25
src/util/logUtils.ts
Normal 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)
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user