Skip to content

Commit

Permalink
fix(common): when passing class functions to logger methods
Browse files Browse the repository at this point in the history
  • Loading branch information
micalevisk committed Oct 13, 2023
1 parent ecdd86f commit 1747683
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
16 changes: 12 additions & 4 deletions packages/common/services/console-logger.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,10 +245,18 @@ export class ConsoleLogger implements LoggerService {
}

protected stringifyMessage(message: unknown, logLevel: LogLevel) {
// If the message is a function, call it and re-resolve its value.
return isFunction(message)
? this.stringifyMessage(message(), logLevel)
: isPlainObject(message) || Array.isArray(message)
if (isFunction(message)) {
const messageAsStr = Function.prototype.toString.call(message);
const isClass = messageAsStr.startsWith('class ');
if (isClass) {
// If the message is a class, we will display the class name.
return this.stringifyMessage(message.name, logLevel);
}
// If the message is a non-class function, call it and re-resolve its value.
return this.stringifyMessage(message(), logLevel);
}

return isPlainObject(message) || Array.isArray(message)
? `${this.colorize('Object:', logLevel)}\n${JSON.stringify(
message,
(key, value) =>
Expand Down
28 changes: 28 additions & 0 deletions packages/common/test/services/logger.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,34 @@ describe('Logger', () => {
);
});
});

describe('classes for message', () => {
let processStdoutWriteSpy: sinon.SinonSpy;

beforeEach(() => {
processStdoutWriteSpy = sinon.spy(process.stdout, 'write');
});
afterEach(() => {
processStdoutWriteSpy.restore();
});

it("should display class's name or empty for anonymous classes", () => {
const logger = new ConsoleLogger();

// in-line anonymous class
logger.log(class {});

// named class
class Test {
#privateField = 'private field';
publicField = 'public field';
}
logger.log(Test);

expect(processStdoutWriteSpy.firstCall.firstArg).to.include('');
expect(processStdoutWriteSpy.secondCall.firstArg).to.include(Test.name);
});
});
});

describe('[instance methods]', () => {
Expand Down

0 comments on commit 1747683

Please sign in to comment.