Skip to content

Commit d588ada

Browse files
committed
refactor(NODE-6616): short circuit EJSON stringifying
1 parent e2aa15c commit d588ada

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

src/mongo_logger.ts

+33-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { inspect, promisify } from 'util';
2+
import { isUint8Array } from 'util/types';
23

34
import { type Document, EJSON, type EJSONOptions, type ObjectId } from './bson';
45
import type { CommandStartedEvent } from './cmap/command_monitoring_events';
@@ -421,13 +422,44 @@ export function stringifyWithMaxLen(
421422
): string {
422423
let strToTruncate = '';
423424

425+
let currentLength = 0;
426+
const maxDocumentLengthEnsurer = function maxDocumentLengthEnsurer(key: string, value: any) {
427+
if (currentLength >= maxDocumentLength) {
428+
return undefined;
429+
}
430+
431+
currentLength += key.length + 4;
432+
433+
if (typeof value === 'string') {
434+
currentLength += value.length;
435+
} else if (typeof value === 'number' || typeof value === 'bigint') {
436+
currentLength += 20;
437+
} else if (typeof value === 'boolean') {
438+
currentLength += value ? 4 : 5;
439+
} else if (value != null && typeof value === 'object' && '_bsontype' in value) {
440+
if (isUint8Array(value.buffer)) {
441+
currentLength += (value.buffer.byteLength + value.buffer.byteLength * 0.5) | 0;
442+
} else if (value._bsontype === 'Binary') {
443+
currentLength += (value.position + value.position * 0.3) | 0;
444+
} else if (value._bsontype === 'Code') {
445+
currentLength += value.code.length;
446+
}
447+
}
448+
449+
return value;
450+
};
451+
424452
if (typeof value === 'string') {
425453
strToTruncate = value;
426454
} else if (typeof value === 'function') {
427455
strToTruncate = value.name;
428456
} else {
429457
try {
430-
strToTruncate = EJSON.stringify(value, options);
458+
if (maxDocumentLength !== 0) {
459+
strToTruncate = EJSON.stringify(value, maxDocumentLengthEnsurer, 0, options);
460+
} else {
461+
strToTruncate = EJSON.stringify(value, options);
462+
}
431463
} catch (e) {
432464
strToTruncate = `Extended JSON serialization failed with: ${e.message}`;
433465
}

0 commit comments

Comments
 (0)