Skip to content

Commit

Permalink
chore(patch): send log to Datadog to enable logs correlation
Browse files Browse the repository at this point in the history
  • Loading branch information
PauloGoncalvesBH committed Sep 13, 2023
1 parent 0d21a87 commit 6cf21c2
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 12 deletions.
6 changes: 3 additions & 3 deletions src/middlewares/error-handler.js
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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'
})
Expand All @@ -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 })
Expand Down
15 changes: 15 additions & 0 deletions src/utils/logger.js
Original file line number Diff line number Diff line change
@@ -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 }
33 changes: 24 additions & 9 deletions test/integration/outros/error-handler.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand All @@ -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 () => {
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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' }
}))
})
})

0 comments on commit 6cf21c2

Please sign in to comment.