Fixed WinstongLogger logging fields which are not castable to a string

Signed-off-by: Harrison Hogg <hhogg@spotify.com>
This commit is contained in:
Harrison Hogg
2024-11-26 11:54:29 +00:00
parent 4c565e181b
commit f5336f07b2
2 changed files with 35 additions and 4 deletions
@@ -93,4 +93,28 @@ describe('WinstonLogger', () => {
expect.any(Function),
);
});
it('gracefully handles fields that are not castable to a string', () => {
const mockTransport = new Transport({
log: jest.fn(),
logv: jest.fn(),
});
const logger = WinstonLogger.create({
transports: [mockTransport],
});
logger.error('something went wrong', {
field: Object.create(null),
});
expect(mockTransport.log).toHaveBeenCalledWith(
expect.objectContaining({
[MESSAGE]: expect.stringContaining(
'[field value not castable to string]',
),
}),
expect.any(Function),
);
});
});
@@ -147,10 +147,17 @@ export class WinstonLogger implements RootLoggerService {
const prefixColor = colorizer.colorize('prefix', prefix);
const extraFields = Object.entries(fields)
.map(
([key, value]) =>
`${colorizer.colorize('field', `${key}`)}=${value}`,
)
.map(([key, value]) => {
let stringValue = '';
try {
stringValue = `${value}`;
} catch (e) {
stringValue = '[field value not castable to string]';
}
return `${colorizer.colorize('field', `${key}`)}=${stringValue}`;
})
.join(' ');
return `${timestampColor} ${prefixColor} ${level} ${message} ${extraFields}`;