Skip to content

Commit b9f2d47

Browse files
committed
nodejs util inspect custom symol
1 parent fee524c commit b9f2d47

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

packages/logger/src/utils.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,8 @@ function isPrimitive(val: unknown): val is string | number | boolean {
128128
return val !== Object(val);
129129
}
130130

131+
const nodejsCustomInspectSy = Symbol.for('nodejs.util.inspect.custom');
132+
131133
function objectifyClass(val: unknown): Record<string, unknown> {
132134
if (
133135
// simply empty
@@ -145,6 +147,19 @@ function objectifyClass(val: unknown): Record<string, unknown> {
145147
// if the object has a toJSON method, use it - always
146148
return val.toJSON();
147149
}
150+
if (
151+
typeof val === 'object' &&
152+
nodejsCustomInspectSy in val &&
153+
typeof val[nodejsCustomInspectSy] === 'function'
154+
) {
155+
// > Custom [util.inspect.custom](depth, opts, inspect) functions typically return a string but may return a value of any type that will be formatted accordingly by util.inspect().
156+
return {
157+
[nodejsCustomInspectSy.toString()]: unwrapAttrVal(
158+
val[nodejsCustomInspectSy](Infinity, {}),
159+
),
160+
class: val.constructor.name,
161+
};
162+
}
148163
const props: Record<string, unknown> = {};
149164
for (const propName of Object.getOwnPropertyNames(val)) {
150165
props[propName] = unwrapAttrVal(val[propName as keyof typeof val]);

packages/logger/tests/logger.test.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -784,3 +784,28 @@ it('should change child log level only on child', () => {
784784
]
785785
`);
786786
});
787+
788+
it('should log using nodejs.util.inspect.custom symbol', () => {
789+
const [log, writer] = createTLogger();
790+
791+
class Inspect {
792+
[Symbol.for('nodejs.util.inspect.custom')]() {
793+
return 'Ok good';
794+
}
795+
}
796+
797+
log.info(new Inspect(), 'sy');
798+
799+
expect(writer.logs).toMatchInlineSnapshot(`
800+
[
801+
{
802+
"attrs": {
803+
"Symbol(nodejs.util.inspect.custom)": "Ok good",
804+
"class": "Inspect",
805+
},
806+
"level": "info",
807+
"msg": "sy",
808+
},
809+
]
810+
`);
811+
});

0 commit comments

Comments
 (0)