Merge pull request #27831 from backstage/winston-logger/handle-non-castable-string

Fixed WinstonLogger logging fields which are not castable to a string
This commit is contained in:
Harrison Hogg
2024-11-29 17:17:27 +00:00
committed by GitHub
3 changed files with 40 additions and 4 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/backend-defaults': patch
---
Fixed an issue in the WinstonLogger where Errors thrown and given to logger.error with field values that could not be cast to a string would throw a TypeError
@@ -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}`;