diff --git a/src/middlewares/error-handler.js b/src/middlewares/error-handler.js index 56700169..21b5687f 100644 --- a/src/middlewares/error-handler.js +++ b/src/middlewares/error-handler.js @@ -1,5 +1,6 @@ const { INTERNAL_ERROR, TIMEOUT } = require('../utils/constants') const montarMensagemDeErroDeSchema = require('../utils/montarMensagemDeErroDeSchema') +const { log } = require('../utils/logger') function errorHandler (error, _req, res, _next) { const erroDeSchema = error.name === 'ValidationError' @@ -8,7 +9,7 @@ function errorHandler (error, _req, res, _next) { } // https://github.com/expressjs/body-parser#errors if (error.type === 'entity.parse.failed') { - console.log('lOG - Entity parse error, user sending request without proper quotation marks.') + log({ message: 'Entity parse error, user sending request without proper quotation marks.' }) return res.status(400).json({ message: 'Adicione aspas em todos os valores. Para mais informações acesse a issue https://github.com/ServeRest/ServeRest/issues/225' }) @@ -24,8 +25,7 @@ function errorHandler (error, _req, res, _next) { return res.status(408).json({ message: TIMEOUT }) } - console.error('lOG - Error 500:', error) - console.error('lOG - Request:', _req) + log({ level: 'error', message: error?.type || error }) if (error.type) { return res.status(500).json({ message: INTERNAL_ERROR, error: error.type }) diff --git a/src/utils/logger.js b/src/utils/logger.js new file mode 100644 index 00000000..e664ecc6 --- /dev/null +++ b/src/utils/logger.js @@ -0,0 +1,15 @@ +const tracer = require('dd-trace') +const formats = require('dd-trace/ext/formats') + +function log ({ level = 'alert', message }) { + const span = tracer.scope().active() + const time = new Date().toISOString() + const record = { time, level, message } + /* istanbul ignore next */ + if (span) { + tracer.inject(span.context(), formats.LOG, record) + } + console.log(record) +} + +module.exports = { log } diff --git a/test/integration/outros/error-handler.test.js b/test/integration/outros/error-handler.test.js index 46333576..153c06c9 100644 --- a/test/integration/outros/error-handler.test.js +++ b/test/integration/outros/error-handler.test.js @@ -5,6 +5,9 @@ const sandbox = sinon.createSandbox() const carrinhosService = require('../../../src/services/carrinhos-service.js') describe('Error handler', () => { + const fixedDate = 1694600359846 + beforeEach(() => sandbox.useFakeTimers({ now: fixedDate })) + afterEach(() => sandbox.restore()) it('Deve retornar erro informando sobre formatação quando encontrar erro "entity.parse.failed" - @skipE2E', async () => { @@ -17,7 +20,11 @@ describe('Error handler', () => { message: 'Adicione aspas em todos os valores. Para mais informações acesse a issue https://github.com/ServeRest/ServeRest/issues/225' }) sinon.assert.calledOnce(consoleLogStub) - sinon.assert.calledOnceWithExactly(consoleLogStub, 'lOG - Entity parse error, user sending request without proper quotation marks.') + sinon.assert.calledWith(consoleLogStub, sinon.match({ + time: new Date(fixedDate).toISOString(), + level: 'alert', + message: 'Entity parse error, user sending request without proper quotation marks.' + })) }) it('Deve retornar erro "Payload too large" quando encontrar erro "entity.too.large" - @skipE2E', async () => { @@ -42,7 +49,7 @@ describe('Error handler', () => { }) it('Deve informar para abrir issue ao ocorrer erro 500 com o tipo de erro ao ter "error.type" - @skipE2E', async () => { - const consoleErrorStub = sandbox.stub(console, 'error') + const consoleLogStub = sandbox.stub(console, 'log') sandbox.stub(carrinhosService, 'getAll').throws({ type: 'test' }) const { body } = await request.get('/carrinhos').expect(500) @@ -51,13 +58,17 @@ describe('Error handler', () => { message: 'Abra uma issue informando essa resposta. https://github.com/ServeRest/ServeRest/issues', error: 'test' }) - sinon.assert.calledTwice(consoleErrorStub) - sinon.assert.calledWith(consoleErrorStub.firstCall, 'lOG - Error 500:', sinon.match.any) - sinon.assert.calledWith(consoleErrorStub.secondCall, 'lOG - Request:', sinon.match.any) + + sinon.assert.calledOnce(consoleLogStub) + sinon.assert.calledWith(consoleLogStub, sinon.match({ + time: new Date(fixedDate).toISOString(), + level: 'error', + message: 'test' + })) }) it('Deve informar para abrir issue ao ocorrer erro 500 com toda a mensagem de erro ao não ter "error.type" - @skipE2E', async () => { - const consoleErrorStub = sandbox.stub(console, 'error') + const consoleLogStub = sandbox.stub(console, 'log') sandbox.stub(carrinhosService, 'getAll').throws('Teste de erro 500') const { body } = await request.get('/carrinhos').expect(500) @@ -66,8 +77,12 @@ describe('Error handler', () => { message: 'Abra uma issue informando essa resposta. https://github.com/ServeRest/ServeRest/issues', error: { name: 'Teste de erro 500' } }) - sinon.assert.calledTwice(consoleErrorStub) - sinon.assert.calledWith(consoleErrorStub.firstCall, 'lOG - Error 500:', sinon.match.any) - sinon.assert.calledWith(consoleErrorStub.secondCall, 'lOG - Request:', sinon.match.any) + + sinon.assert.calledOnce(consoleLogStub) + sinon.assert.calledWith(consoleLogStub, sinon.match({ + time: new Date(fixedDate).toISOString(), + level: 'error', + message: { name: 'Teste de erro 500' } + })) }) })