Skip to content

Commit 641cae8

Browse files
authored
Fix logging for objects that define toJSON (#916)
* attempt to use toJSON before removeCircular * changelog * formats
1 parent e88a15a commit 641cae8

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
- Adds support for setting user labels on functions via `runWith()`.
22
- Adds support for FIREBASE_CONFIG env as the name of a JSON file
3+
- Fixes an issue where objects that define `toJSON` could not be logged successfully (#907).
34
- Formalize module exports. Loggers can now be accessed at 'firebase-functions/logger' and 'firebase-functions/logger/compat'
45
- Fixes an issue where Remote Config coiuld not be emulated in Windows machines on the classic Command Prompt.

spec/logger.spec.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { expect } from 'chai';
2+
23
import * as logger from '../src/logger';
34

45
const SUPPORTS_STRUCTURED_LOGS =
@@ -109,6 +110,22 @@ describe(`logger (${
109110
});
110111
});
111112

113+
it('should not break on objects that override toJSON', () => {
114+
const obj: any = { a: new Date('August 26, 1994 12:24:00Z') };
115+
116+
const entry: logger.LogEntry = {
117+
severity: 'ERROR',
118+
message: 'testing toJSON',
119+
obj,
120+
};
121+
logger.write(entry);
122+
expectStderr({
123+
severity: 'ERROR',
124+
message: 'testing toJSON',
125+
obj: { a: '1994-08-26T12:24:00.000Z' },
126+
});
127+
});
128+
112129
it('should not alter parameters that are logged', () => {
113130
const circ: any = { b: 'foo' };
114131
circ.array = [circ];

src/logger/index.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@ function removeCircular(obj: any, refs: any[] = []): any {
3535
if (typeof obj !== 'object' || !obj) {
3636
return obj;
3737
}
38+
// If the object defines its own toJSON, prefer that.
39+
if (obj['toJSON']) {
40+
return obj.toJSON();
41+
}
3842
if (refs.includes(obj)) {
3943
return '[Circular]';
4044
} else {

0 commit comments

Comments
 (0)