File size: 8,522 Bytes
23ac194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
'use strict'

const stream = require('node:stream')

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

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

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

  let localhost

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

  t.test('The request id header key can be customized', async (t) => {
    const lines = ['incoming request', 'some log message', 'request completed']
    t.plan(lines.length * 2 + 2)
    const REQUEST_ID = '42'

    const stream = split(JSON.parse)
    const fastify = Fastify({
      logger: { stream, level: 'info' },
      requestIdHeader: 'my-custom-request-id'
    })
    t.teardown(fastify.close.bind(fastify))

    fastify.get('/', (req, reply) => {
      t.equal(req.id, REQUEST_ID)
      req.log.info('some log message')
      reply.send({ id: req.id })
    })

    const response = await fastify.inject({ method: 'GET', url: '/', headers: { 'my-custom-request-id': REQUEST_ID } })
    const body = await response.json()
    t.equal(body.id, REQUEST_ID)

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

  t.test('The request id header key can be ignored', async (t) => {
    const lines = ['incoming request', 'some log message', 'request completed']
    t.plan(lines.length * 2 + 2)
    const REQUEST_ID = 'ignore-me'

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

    fastify.get('/', (req, reply) => {
      t.equal(req.id, 'req-1')
      req.log.info('some log message')
      reply.send({ id: req.id })
    })
    const response = await fastify.inject({ method: 'GET', url: '/', headers: { 'request-id': REQUEST_ID } })
    const body = await response.json()
    t.equal(body.id, 'req-1')

    for await (const [line] of on(stream, 'data')) {
      t.equal(line.reqId, 'req-1')
      t.equal(line.msg, lines.shift(), 'message is set')
      if (lines.length === 0) break
    }
  })

  t.test('The request id header key can be customized along with a custom id generator', async (t) => {
    const REQUEST_ID = '42'
    const matches = [
      { reqId: REQUEST_ID, msg: /incoming request/ },
      { reqId: REQUEST_ID, msg: /some log message/ },
      { reqId: REQUEST_ID, msg: /request completed/ },
      { reqId: 'foo', msg: /incoming request/ },
      { reqId: 'foo', msg: /some log message 2/ },
      { reqId: 'foo', msg: /request completed/ }
    ]
    t.plan(matches.length + 4)

    const stream = split(JSON.parse)
    const fastify = Fastify({
      logger: { stream, level: 'info' },
      requestIdHeader: 'my-custom-request-id',
      genReqId (req) {
        return 'foo'
      }
    })
    t.teardown(fastify.close.bind(fastify))

    fastify.get('/one', (req, reply) => {
      t.equal(req.id, REQUEST_ID)
      req.log.info('some log message')
      reply.send({ id: req.id })
    })

    fastify.get('/two', (req, reply) => {
      t.equal(req.id, 'foo')
      req.log.info('some log message 2')
      reply.send({ id: req.id })
    })

    {
      const response = await fastify.inject({ method: 'GET', url: '/one', headers: { 'my-custom-request-id': REQUEST_ID } })
      const body = await response.json()
      t.equal(body.id, REQUEST_ID)
    }

    {
      const response = await fastify.inject({ method: 'GET', url: '/two' })
      const body = await response.json()
      t.equal(body.id, 'foo')
    }

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

  t.test('The request id header key can be ignored along with a custom id generator', async (t) => {
    const REQUEST_ID = 'ignore-me'
    const matches = [
      { reqId: 'foo', msg: /incoming request/ },
      { reqId: 'foo', msg: /some log message/ },
      { reqId: 'foo', msg: /request completed/ },
      { reqId: 'foo', msg: /incoming request/ },
      { reqId: 'foo', msg: /some log message 2/ },
      { reqId: 'foo', msg: /request completed/ }
    ]
    t.plan(matches.length + 4)

    const stream = split(JSON.parse)
    const fastify = Fastify({
      logger: { stream, level: 'info' },
      requestIdHeader: false,
      genReqId (req) {
        return 'foo'
      }
    })
    t.teardown(fastify.close.bind(fastify))

    fastify.get('/one', (req, reply) => {
      t.equal(req.id, 'foo')
      req.log.info('some log message')
      reply.send({ id: req.id })
    })

    fastify.get('/two', (req, reply) => {
      t.equal(req.id, 'foo')
      req.log.info('some log message 2')
      reply.send({ id: req.id })
    })

    {
      const response = await fastify.inject({ method: 'GET', url: '/one', headers: { 'request-id': REQUEST_ID } })
      const body = await response.json()
      t.equal(body.id, 'foo')
    }

    {
      const response = await fastify.inject({ method: 'GET', url: '/two' })
      const body = await response.json()
      t.equal(body.id, 'foo')
    }

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

  t.test('The request id log label can be changed', async (t) => {
    const REQUEST_ID = '42'
    const matches = [
      { traceId: REQUEST_ID, msg: /incoming request/ },
      { traceId: REQUEST_ID, msg: /some log message/ },
      { traceId: REQUEST_ID, msg: /request completed/ }
    ]
    t.plan(matches.length + 2)

    const stream = split(JSON.parse)
    const fastify = Fastify({
      logger: { stream, level: 'info' },
      requestIdHeader: 'my-custom-request-id',
      requestIdLogLabel: 'traceId'
    })
    t.teardown(fastify.close.bind(fastify))

    fastify.get('/one', (req, reply) => {
      t.equal(req.id, REQUEST_ID)
      req.log.info('some log message')
      reply.send({ id: req.id })
    })

    {
      const response = await fastify.inject({ method: 'GET', url: '/one', headers: { 'my-custom-request-id': REQUEST_ID } })
      const body = await response.json()
      t.equal(body.id, REQUEST_ID)
    }

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

  t.test('should redact the authorization header if so specified', async (t) => {
    const lines = [
      { msg: /Server listening at/ },
      { req: { headers: { authorization: '[Redacted]' } }, msg: 'incoming request' },
      { res: { statusCode: 200 }, msg: 'request completed' }
    ]
    t.plan(lines.length + 3)
    const stream = split(JSON.parse)
    const fastify = Fastify({
      logger: {
        stream,
        redact: ['req.headers.authorization'],
        level: 'info',
        serializers: {
          req (req) {
            return {
              method: req.method,
              url: req.url,
              headers: req.headers,
              hostname: req.hostname,
              remoteAddress: req.ip,
              remotePort: req.socket.remotePort
            }
          }
        }
      }
    })
    t.teardown(fastify.close.bind(fastify))

    fastify.get('/', function (req, reply) {
      t.same(req.headers.authorization, 'Bearer abcde')
      reply.send({ hello: 'world' })
    })

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

    await request({
      method: 'GET',
      path: '/',
      host: localhost,
      port: fastify.server.address().port,
      headers: {
        authorization: 'Bearer abcde'
      }
    }, function (response, body) {
      t.equal(response.statusCode, 200)
      t.same(body, JSON.stringify({ hello: 'world' }))
    })

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

  t.test('should not throw error when serializing custom req', (t) => {
    t.plan(1)

    const lines = []
    const dest = new stream.Writable({
      write: function (chunk, enc, cb) {
        lines.push(JSON.parse(chunk))
        cb()
      }
    })
    const fastify = Fastify({ logger: { level: 'info', stream: dest } })
    t.teardown(fastify.close.bind(fastify))

    fastify.log.info({ req: {} })

    t.same(lines[0].req, {})
  })
})