diff --git a/src/LoggerHelper.ts b/src/LoggerHelper.ts index d7b7c39e..0db591f5 100644 --- a/src/LoggerHelper.ts +++ b/src/LoggerHelper.ts @@ -274,28 +274,34 @@ export class LoggerHelper { : `${lineNumber}`; } - public static traverseObjectRecursively( + public static cloneObjectRecursively( obj: T, - maskValuesFn: (key: number | string, obj: T) => T, - done: unknown[] = [] + maskValuesFn: (key: number | string, value: unknown) => unknown, + done: unknown[] = [], + clonedObject: T = Object.create(Object.getPrototypeOf(obj)) as T ): T { + done.push(obj); Object.keys(obj).forEach((currentKey: string | number) => { if (!done.includes(obj[currentKey])) { - done.push(obj[currentKey]); - if (obj[currentKey] != null && typeof obj[currentKey] === "object") { - const maskedObj = maskValuesFn(currentKey, obj); - obj[currentKey] = LoggerHelper.traverseObjectRecursively( - maskedObj[currentKey], + if (obj[currentKey] == null) { + clonedObject[currentKey] = obj[currentKey]; + } else if (typeof obj[currentKey] !== "object") { + clonedObject[currentKey] = maskValuesFn(currentKey, obj[currentKey]); + } else { + clonedObject[currentKey] = LoggerHelper.cloneObjectRecursively( + obj[currentKey], maskValuesFn, - done + done, + clonedObject[currentKey] ); - } else { - obj = maskValuesFn(currentKey, obj); } + } else { + // cicrular detected: point to itself to make inspect printout [circular] + clonedObject[currentKey] = clonedObject; } }); - return obj; + return clonedObject as T; } public static logObjectMaskValuesOfKeys( @@ -307,7 +313,7 @@ export class LoggerHelper { return obj; } - const maskValuesFn = (key: number | string, obj: T): T => { + const maskValuesFn = (key: number | string, value: unknown): unknown => { const keysLowerCase: ( | string | number @@ -319,11 +325,11 @@ export class LoggerHelper { typeof key === "string" ? key.toLowerCase() : key ) ) { - obj[key] = maskPlaceholder; + return maskPlaceholder; } - return obj; + return value; }; - return LoggerHelper.traverseObjectRecursively(obj, maskValuesFn); + return LoggerHelper.cloneObjectRecursively(obj, maskValuesFn); } } diff --git a/src/LoggerWithoutCallSite.ts b/src/LoggerWithoutCallSite.ts index f886363c..e591ac33 100644 --- a/src/LoggerWithoutCallSite.ts +++ b/src/LoggerWithoutCallSite.ts @@ -855,7 +855,7 @@ export class LoggerWithoutCallSite { return this._maskAny(format(formatParam, ...param)); } - private _maskValuesOfKeys(object: object | null) { + private _maskValuesOfKeys(object: T): T { return LoggerHelper.logObjectMaskValuesOfKeys( object, this.settings.maskValuesOfKeys, @@ -863,7 +863,7 @@ export class LoggerWithoutCallSite { ); } - private _maskAny(str: string) { + private _maskAny(str: string): string { const formattedStr = str; return this._maskAnyRegExp != null