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78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
'use strict'

const stream = require('node:stream')

const t = require('tap')
const split = require('split2')
const pino = require('pino')

const Fastify = require('../../fastify')
const helper = require('../helper')
const { once, on } = stream
const { request } = require('./logger-test-utils')

t.test('logging', (t) => {
  t.setTimeout(60000)

  let localhost
  let localhostForURL

  t.plan(13)

  t.before(async function () {
    [localhost, localhostForURL] = await helper.getLoopbackHost()
  })

  t.test('The default 404 handler logs the incoming request', async (t) => {
    const lines = ['incoming request', 'Route GET:/not-found not found', 'request completed']
    t.plan(lines.length + 1)

    const stream = split(JSON.parse)

    const loggerInstance = pino({ level: 'trace' }, stream)

    const fastify = Fastify({
      loggerInstance
    })
    t.teardown(fastify.close.bind(fastify))

    await fastify.ready()

    {
      const response = await fastify.inject({ method: 'GET', url: '/not-found' })
      t.equal(response.statusCode, 404)
    }

    for await (const [line] of on(stream, 'data')) {
      t.equal(line.msg, lines.shift())
      if (lines.length === 0) break
    }
  })

  t.test('should not rely on raw request to log errors', async (t) => {
    const lines = [
      { msg: /Server listening at/ },
      { level: 30, msg: 'incoming request' },
      { res: { statusCode: 415 }, msg: 'something happened' },
      { res: { statusCode: 415 }, msg: 'request completed' }
    ]
    t.plan(lines.length + 1)
    const stream = split(JSON.parse)
    const fastify = Fastify({
      logger: {
        stream,
        level: 'info'
      }
    })
    t.teardown(fastify.close.bind(fastify))
    fastify.get('/error', function (req, reply) {
      t.ok(req.log)
      reply.status(415).send(new Error('something happened'))
    })

    await fastify.ready()
    await fastify.listen({ port: 0, host: localhost })

    await request(`http://${localhostForURL}:` + fastify.server.address().port + '/error')

    for await (const [line] of on(stream, 'data')) {
      t.match(line, lines.shift())
      if (lines.length === 0) break
    }
  })

  t.test('should log the error if no error handler is defined', async (t) => {
    const lines = [
      { msg: /Server listening at/ },
      { msg: 'incoming request' },
      { level: 50, msg: 'a generic error' },
      { res: { statusCode: 500 }, msg: 'request completed' }
    ]
    t.plan(lines.length + 1)

    const stream = split(JSON.parse)
    const fastify = Fastify({
      logger: {
        stream,
        level: 'info'
      }
    })
    t.teardown(fastify.close.bind(fastify))

    fastify.get('/error', function (req, reply) {
      t.ok(req.log)
      reply.send(new Error('a generic error'))
    })

    await fastify.ready()
    await fastify.listen({ port: 0, host: localhost })

    await request(`http://${localhostForURL}:` + fastify.server.address().port + '/error')

    for await (const [line] of on(stream, 'data')) {
      t.match(line, lines.shift())
      if (lines.length === 0) break
    }
  })

  t.test('should log as info if error status code >= 400 and < 500 if no error handler is defined', async (t) => {
    const lines = [
      { msg: /Server listening at/ },
      { msg: 'incoming request' },
      { level: 30, msg: 'a 400 error' },
      { res: { statusCode: 400 }, msg: 'request completed' }
    ]
    t.plan(lines.length + 1)
    const stream = split(JSON.parse)
    const fastify = Fastify({
      logger: {
        stream,
        level: 'info'
      }
    })
    t.teardown(fastify.close.bind(fastify))

    fastify.get('/400', function (req, reply) {
      t.ok(req.log)
      reply.send(Object.assign(new Error('a 400 error'), { statusCode: 400 }))
    })
    fastify.get('/503', function (req, reply) {
      t.ok(req.log)
      reply.send(Object.assign(new Error('a 503 error'), { statusCode: 503 }))
    })

    await fastify.ready()
    await fastify.listen({ port: 0, host: localhost })

    await request(`http://${localhostForURL}:` + fastify.server.address().port + '/400')

    for await (const [line] of on(stream, 'data')) {
      t.match(line, lines.shift())
      if (lines.length === 0) break
    }
  })

  t.test('should log as error if error status code >= 500 if no error handler is defined', async (t) => {
    const lines = [
      { msg: /Server listening at/ },
      { msg: 'incoming request' },
      { level: 50, msg: 'a 503 error' },
      { res: { statusCode: 503 }, msg: 'request completed' }
    ]
    t.plan(lines.length + 1)
    const stream = split(JSON.parse)
    const fastify = Fastify({
      logger: {
        stream,
        level: 'info'
      }
    })
    t.teardown(fastify.close.bind(fastify))
    fastify.get('/503', function (req, reply) {
      t.ok(req.log)
      reply.send(Object.assign(new Error('a 503 error'), { statusCode: 503 }))
    })

    await fastify.ready()
    await fastify.listen({ port: 0, host: localhost })

    await request(`http://${localhostForURL}:` + fastify.server.address().port + '/503')

    for await (const [line] of on(stream, 'data')) {
      t.match(line, lines.shift())
      if (lines.length === 0) break
    }
  })

  t.test('should not log the error if error handler is defined and it does not error', async (t) => {
    const lines = [
      { msg: /Server listening at/ },
      { level: 30, msg: 'incoming request' },
      { res: { statusCode: 200 }, msg: 'request completed' }
    ]
    t.plan(lines.length + 2)
    const stream = split(JSON.parse)
    const fastify = Fastify({
      logger: {
        stream,
        level: 'info'
      }
    })
    t.teardown(fastify.close.bind(fastify))
    fastify.get('/error', function (req, reply) {
      t.ok(req.log)
      reply.send(new Error('something happened'))
    })
    fastify.setErrorHandler((err, req, reply) => {
      t.ok(err)
      reply.send('something bad happened')
    })

    await fastify.ready()
    await fastify.listen({ port: 0, host: localhost })

    await request(`http://${localhostForURL}:` + fastify.server.address().port + '/error')

    for await (const [line] of on(stream, 'data')) {
      t.match(line, lines.shift())
      if (lines.length === 0) break
    }
  })

  t.test('reply.send logs an error if called twice in a row', async (t) => {
    const lines = [
      'incoming request',
      'request completed',
      'Reply was already sent, did you forget to "return reply" in "/" (GET)?',
      'Reply was already sent, did you forget to "return reply" in "/" (GET)?'
    ]
    t.plan(lines.length + 1)

    const stream = split(JSON.parse)
    const loggerInstance = pino(stream)

    const fastify = Fastify({
      loggerInstance
    })
    t.teardown(fastify.close.bind(fastify))

    fastify.get('/', (req, reply) => {
      reply.send({ hello: 'world' })
      reply.send({ hello: 'world2' })
      reply.send({ hello: 'world3' })
    })

    const response = await fastify.inject({ method: 'GET', url: '/' })
    const body = await response.json()
    t.same(body, { hello: 'world' })

    for await (const [line] of on(stream, 'data')) {
      t.same(line.msg, lines.shift())
      if (lines.length === 0) break
    }
  })

  t.test('should not log incoming request and outgoing response when disabled', async (t) => {
    t.plan(1)
    const stream = split(JSON.parse)
    const fastify = Fastify({ disableRequestLogging: true, logger: { level: 'info', stream } })
    t.teardown(fastify.close.bind(fastify))

    fastify.get('/500', (req, reply) => {
      reply.code(500).send(Error('500 error'))
    })

    await fastify.ready()

    await fastify.inject({ method: 'GET', url: '/500' })

    // no more readable data
    t.equal(stream.readableLength, 0)
  })

  t.test('should not log incoming request, outgoing response  and route not found for 404 onBadUrl when disabled', async (t) => {
    t.plan(1)
    const stream = split(JSON.parse)
    const fastify = Fastify({ disableRequestLogging: true, logger: { level: 'info', stream } })
    t.teardown(fastify.close.bind(fastify))

    await fastify.ready()

    await fastify.inject({ method: 'GET', url: '/%c0' })

    // no more readable data
    t.equal(stream.readableLength, 0)
  })

  t.test('defaults to info level', async (t) => {
    const lines = [
      { reqId: /req-/, req: { method: 'GET' }, msg: 'incoming request' },
      { reqId: /req-/, res: { statusCode: 200 }, msg: 'request completed' }
    ]
    t.plan(lines.length * 2 + 1)
    const stream = split(JSON.parse)
    const fastify = Fastify({
      logger: {
        stream
      }
    })
    t.teardown(fastify.close.bind(fastify))

    fastify.get('/', function (req, reply) {
      t.ok(req.log)
      reply.send({ hello: 'world' })
    })

    await fastify.ready()
    await fastify.listen({ port: 0 })

    await request(`http://${localhostForURL}:` + fastify.server.address().port)

    let id
    for await (const [line] of on(stream, 'data')) {
      // we skip the non-request log
      if (typeof line.reqId !== 'string') continue
      if (id === undefined && line.reqId) id = line.reqId
      if (id !== undefined && line.reqId) t.equal(line.reqId, id)
      t.match(line, lines.shift())
      if (lines.length === 0) break
    }
  })

  t.test('test log stream', async (t) => {
    const lines = [
      { msg: /^Server listening at / },
      { reqId: /req-/, req: { method: 'GET' }, msg: 'incoming request' },
      { reqId: /req-/, res: { statusCode: 200 }, msg: 'request completed' }
    ]
    t.plan(lines.length + 3)

    const stream = split(JSON.parse)
    const fastify = Fastify({
      logger: {
        stream,
        level: 'info'
      }
    })
    t.teardown(fastify.close.bind(fastify))

    fastify.get('/', function (req, reply) {
      t.ok(req.log)
      reply.send({ hello: 'world' })
    })

    await fastify.ready()
    await fastify.listen({ port: 0, host: localhost })

    await request(`http://${localhostForURL}:` + fastify.server.address().port)

    let id
    for await (const [line] of on(stream, 'data')) {
      if (id === undefined && line.reqId) id = line.reqId
      if (id !== undefined && line.reqId) t.equal(line.reqId, id)
      t.match(line, lines.shift())
      if (lines.length === 0) break
    }
  })

  t.test('test error log stream', async (t) => {
    const lines = [
      { msg: /^Server listening at / },
      { reqId: /req-/, req: { method: 'GET' }, msg: 'incoming request' },
      { reqId: /req-/, res: { statusCode: 500 }, msg: 'kaboom' },
      { reqId: /req-/, res: { statusCode: 500 }, msg: 'request completed' }
    ]
    t.plan(lines.length + 4)

    const stream = split(JSON.parse)
    const fastify = Fastify({
      logger: {
        stream,
        level: 'info'
      }
    })
    t.teardown(fastify.close.bind(fastify))

    fastify.get('/error', function (req, reply) {
      t.ok(req.log)
      reply.send(new Error('kaboom'))
    })

    await fastify.ready()
    await fastify.listen({ port: 0, host: localhost })

    await request(`http://${localhostForURL}:` + fastify.server.address().port + '/error')

    let id
    for await (const [line] of on(stream, 'data')) {
      if (id === undefined && line.reqId) id = line.reqId
      if (id !== undefined && line.reqId) t.equal(line.reqId, id)
      t.match(line, lines.shift())
      if (lines.length === 0) break
    }
  })

  t.test('should not log the error if request logging is disabled', async (t) => {
    t.plan(4)

    const stream = split(JSON.parse)
    const fastify = Fastify({
      logger: {
        stream,
        level: 'info'
      },
      disableRequestLogging: true
    })
    t.teardown(fastify.close.bind(fastify))

    fastify.get('/error', function (req, reply) {
      t.ok(req.log)
      reply.send(new Error('a generic error'))
    })

    await fastify.ready()
    await fastify.listen({ port: 0, host: localhost })

    await request(`http://${localhostForURL}:` + fastify.server.address().port + '/error')

    {
      const [line] = await once(stream, 'data')
      t.type(line.msg, 'string')
      t.ok(line.msg.startsWith('Server listening at'), 'message is set')
    }

    // no more readable data
    t.equal(stream.readableLength, 0)
  })
})