-
-
Notifications
You must be signed in to change notification settings - Fork 275
Expand file tree
/
Copy pathlogger.ts
More file actions
205 lines (186 loc) · 4.92 KB
/
logger.ts
File metadata and controls
205 lines (186 loc) · 4.92 KB
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
import pino, { BaseLogger } from 'pino'
import { getConfig } from '../../config'
import { FastifyReply, FastifyRequest } from 'fastify'
import { URL } from 'node:url'
import { normalizeRawError } from '@internal/errors'
const { logLevel, logflareApiKey, logflareSourceToken, logflareEnabled, region } = getConfig()
export const baseLogger = pino({
transport: buildTransport(),
serializers: {
error(error) {
return normalizeRawError(error)
},
res(reply) {
return {
statusCode: reply.statusCode,
headers: whitelistHeaders(reply.getHeaders()),
}
},
req(request) {
return {
region,
traceId: request.id,
method: request.method,
url: redactQueryParamFromRequest(request, [
'token',
'X-Amz-Credential',
'X-Amz-Signature',
'X-Amz-Security-Token',
]),
headers: whitelistHeaders(request.headers),
hostname: request.hostname,
remoteAddress: request.ip,
remotePort: request.socket?.remotePort,
}
},
},
level: logLevel,
timestamp: pino.stdTimeFunctions.isoTime,
})
export const logger = baseLogger.child({ region })
export interface RequestLog {
type: 'request'
req: FastifyRequest
res?: FastifyReply
responseTime: number
error?: Error | unknown
role?: string
owner?: string
operation?: string
resources?: string[]
serverTimes?: { spanName: string; duration: number }[]
}
export interface EventLog {
jodId: string
type: 'event'
event: string
payload: string
objectPath: string
tenantId: string
project: string
resources?: string[]
reqId?: string
}
interface ErrorLog {
type: string
error?: Error | unknown
project?: string
metadata?: string
}
interface InfoLog {
type: string
project?: string
}
export const logSchema = {
info: (logger: BaseLogger, message: string, log: InfoLog) => logger.info(log, message),
warning: (logger: BaseLogger, message: string, log: InfoLog | ErrorLog) =>
logger.warn(log, message),
request: (logger: BaseLogger, message: string, log: RequestLog) => {
if (!log.res) {
logger.warn(log, message)
return
}
const is4xxResponse = statusOfType(log.res.statusCode, 400)
const is5xxResponse = statusOfType(log.res.statusCode, 500)
const logLevel = is4xxResponse ? 'warn' : is5xxResponse ? 'error' : 'info'
logger[logLevel](log, message)
},
error: (logger: BaseLogger, message: string, log: ErrorLog) => logger.error(log, message),
event: (logger: BaseLogger, message: string, log: EventLog) => logger.info(log, message),
}
export function buildTransport(): pino.TransportMultiOptions | undefined {
if (!logflareEnabled) {
return undefined
}
if (!logflareApiKey) {
throw new Error('must provide a logflare api key')
}
if (!logflareSourceToken) {
throw new Error('must provider a logflare source token')
}
return {
targets: [
{
level: logLevel || 'info',
target: './logflare',
options: {},
},
{
level: logLevel || 'info',
target: 'pino/file',
options: {},
},
],
}
}
const whitelistHeaders = (headers: Record<string, unknown>) => {
const responseMetadata: Record<string, unknown> = {}
const allowlistedRequestHeaders = [
'accept',
'cf-connecting-ip',
'cf-ipcountry',
'host',
'user-agent',
'x-forwarded-proto',
'x-forwarded-host',
'x-forwarded-port',
'x-forwarded-prefix',
'referer',
'content-length',
'x-real-ip',
'x-client-info',
'x-forwarded-user-agent',
'x-client-trace-id',
'x-upsert',
'content-type',
'if-none-match',
'if-modified-since',
'upload-metadata',
'upload-length',
'upload-offset',
'tus-resumable',
'range',
]
const allowlistedResponseHeaders = [
'cf-cache-status',
'cf-ray',
'location',
'cache-control',
'content-location',
'content-range',
'content-type',
'content-length',
'date',
'transfer-encoding',
'x-kong-proxy-latency',
'x-kong-upstream-latency',
'sb-gateway-mode',
'sb-gateway-version',
'x-transformations',
'expires',
'etag',
'content-disposition',
'last-modified',
]
Object.keys(headers)
.filter(
(header) =>
allowlistedRequestHeaders.includes(header) || allowlistedResponseHeaders.includes(header)
)
.forEach((header) => {
responseMetadata[header.replace(/-/g, '_')] = `${headers[header]}`
})
return responseMetadata
}
export function redactQueryParamFromRequest(req: FastifyRequest, params: string[]) {
const lUrl = new URL(req.url, `${req.protocol}://${req.hostname}`)
params.forEach((param) => {
if (lUrl.searchParams.has(param)) {
lUrl.searchParams.set(param, 'redacted')
}
})
return `${lUrl.pathname}${lUrl.search}`
}
function statusOfType(statusCode: number, ofType: number) {
return statusCode >= ofType && statusCode < ofType + 100
}