forked from delvedor/fastify-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
75 lines (68 loc) · 2.1 KB
/
index.js
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
import 'make-promises-safe'
import Fastify from 'fastify'
import App from './app.js'
// Google Cloud Run will set this environment variable for you, so
// you can also use it to detect if you are running in Cloud Run
const IS_GOOGLE_CLOUD_RUN = process.env.K_SERVICE !== undefined
// Format logs int Stackdriver format (https://cloud.google.com/logging)
const prodLoggerOptions = {
level: 'info',
messageKey: 'message',
timestamp: () => `,"timestamp":"${new Date().toISOString()}"`,
formatters: {
level (label, number) {
switch (label) {
case 'debug':
case 'info':
case 'error':
return { severity: label.toUpperCase() }
case 'warn':
return { severity: 'WARNING' }
case 'fatal':
return { severity: 'CRITICAL' }
default:
return { severity: 'DEFAULT' }
}
},
bindings (bindings) {
return {}
},
log (obj) {
const { req, res, responseTime, ...driver } = obj
if (req != null) {
driver.httpRequest = driver.httpRequest || {}
driver.httpRequest.requestMethod = req.method
driver.httpRequest.requestUrl = (req.raw.socket.encrypted ? 'https://' : 'http://') + req.hostname + req.url
driver.httpRequest.remoteIp = req.ip
driver.httpRequest.userAgent = req.headers['user-agent']
}
if (res != null) {
driver.httpRequest = driver.httpRequest || {}
driver.httpRequest.status = res.statusCode
driver.httpRequest.latency = responseTime / 1000
}
return driver
}
}
}
const devLoggerOptions = {
level: 'info'
}
async function start () {
const fastify = Fastify({
trustProxy: true,
logger: IS_GOOGLE_CLOUD_RUN
? prodLoggerOptions
: devLoggerOptions
})
await fastify.register(App)
// You must listen on the port Cloud Run provides
const port = process.env.PORT || 3000
// You must listen on all IPV4 addresses in Cloud Run
const address = IS_GOOGLE_CLOUD_RUN ? '0.0.0.0' : undefined
await fastify.listen({ port, address })
}
start().catch(err => {
console.error(err)
process.exit(1)
})