forked from vercel/vercel
/
logs.js
325 lines (276 loc) · 7.79 KB
/
logs.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
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
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
#!/usr/bin/env node
// Native
const qs = require('querystring')
// Packages
const mri = require('mri')
const chalk = require('chalk')
const dateformat = require('dateformat')
const io = require('socket.io-client')
// Utilities
const Now = require('../util')
const { handleError, error } = require('../util/error')
const logo = require('../../../util/output/logo')
const { compare, deserialize } = require('../util/logs')
const { maybeURL, normalizeURL, parseInstanceURL } = require('../../../util/url')
const exit = require('../../../util/exit')
const help = () => {
console.log(`
${chalk.bold(`${logo} now logs`)} <deploymentId|url>
${chalk.dim('Options:')}
-h, --help Output usage information
-a, --all Include access logs
-A ${chalk.bold.underline('FILE')}, --local-config=${chalk.bold.underline(
'FILE'
)} Path to the local ${'`now.json`'} file
-Q ${chalk.bold.underline('DIR')}, --global-config=${chalk.bold.underline(
'DIR'
)} Path to the global ${'`.now`'} directory
-d, --debug Debug mode [off]
-f, --follow Wait for additional data [off]
-n ${chalk.bold.underline('NUMBER')} Number of logs [1000]
-q ${chalk.bold.underline('QUERY')}, --query=${chalk.bold.underline(
'QUERY'
)} Search query
-t ${chalk.bold.underline('TOKEN')}, --token=${chalk.bold.underline(
'TOKEN'
)} Login token
--since=${chalk.bold.underline(
'SINCE'
)} Only return logs after date (ISO 8601)
--until=${chalk.bold.underline(
'UNTIL'
)} Only return logs before date (ISO 8601), ignored for ${'`-f`'}
-T, --team Set a custom team scope
-o ${chalk.bold.underline('MODE')}, --output=${chalk.bold.underline(
'MODE'
)} Specify the output format (${Object.keys(logPrinters).join('|')}) [short]
${chalk.dim('Examples:')}
${chalk.gray('–')} Print the logs for the deployment ${chalk.dim(
'`deploymentId`'
)}
${chalk.cyan('$ now logs deploymentId')}
`)
}
let argv
let deploymentIdOrURL
let debug
let apiUrl
let limit
let query
let follow
let types
let outputMode
let since
let until
let instanceId
const main = async ctx => {
argv = mri(ctx.argv.slice(2), {
string: ['query', 'since', 'until', 'output'],
boolean: ['help', 'all', 'debug', 'follow'],
alias: {
help: 'h',
all: 'a',
debug: 'd',
query: 'q',
follow: 'f',
output: 'o'
}
})
argv._ = argv._.slice(1)
deploymentIdOrURL = argv._[0]
if (argv.help || !deploymentIdOrURL || deploymentIdOrURL === 'help') {
help()
await exit(0)
}
try {
since = argv.since ? toSerial(argv.since) : null
} catch (err) {
error(`Invalid date string: ${argv.since}`)
process.exit(1)
}
try {
until = argv.until ? toSerial(argv.until) : null
} catch (err) {
error(`Invalid date string: ${argv.until}`)
process.exit(1)
}
if (maybeURL(deploymentIdOrURL)) {
const normalizedURL = normalizeURL(deploymentIdOrURL)
if (normalizedURL.includes('/')) {
error(`Invalid deployment url: can't include path (${deploymentIdOrURL})`)
process.exit(1)
}
;[deploymentIdOrURL, instanceId] = parseInstanceURL(normalizedURL)
}
debug = argv.debug
apiUrl = ctx.apiUrl
limit = typeof argv.n === 'number' ? argv.n : 1000
query = argv.query || ''
follow = argv.f
types = argv.all ? [] : ['command', 'stdout', 'stderr', 'exit']
outputMode = argv.output in logPrinters ? argv.output : 'short'
const {authConfig: { credentials }, config: { sh }} = ctx
const {token} = credentials.find(item => item.provider === 'sh')
return printLogs({ token, sh })
}
module.exports = async ctx => {
try {
await main(ctx)
} catch (err) {
handleError(err)
process.exit(1)
}
}
function printLogs({ token, sh: { currentTeam } }) {
return new Promise(async (resolve, reject) => {
let buf = []
let init = false
let lastLog
if (!follow) {
onLogs(await fetchLogs({ token, currentTeam, since, until }))
resolve()
}
const isURL = deploymentIdOrURL.includes('.')
const q = qs.stringify({
deploymentId: isURL ? '' : deploymentIdOrURL,
host: isURL ? deploymentIdOrURL : '',
instanceId,
types: types.join(','),
query
})
const socket = io(`https://log-io.zeit.co?${q}`)
socket.on('connect', () => {
if (debug) {
console.log('> [debug] Socket connected')
}
})
socket.on('auth', callback => {
if (debug) {
console.log('> [debug] Socket authenticate')
}
callback(token)
})
socket.on('ready', () => {
if (debug) {
console.log('> [debug] Socket ready')
}
// For the case socket reconnected
const _since = lastLog ? lastLog.serial : since
fetchLogs({ token, currentTeam, since: _since }).then(logs => {
init = true
const m = {}
logs.concat(buf.map(b => b.log)).forEach(l => {
m[l.id] = l
})
buf = []
onLogs(Object.values(m))
})
})
socket.on('logs', l => {
const log = deserialize(l)
let timer
if (init) {
// Wait for other logs for a while
// and sort them in the correct order
timer = setTimeout(() => {
buf.sort((a, b) => compare(a.log, b.log))
const idx = buf.findIndex(b => b.log.id === log.id)
buf.slice(0, idx + 1).forEach(b => {
clearTimeout(b.timer)
onLog(b.log)
})
buf = buf.slice(idx + 1)
}, 300)
}
buf.push({ log, timer })
})
socket.on('disconnect', () => {
if (debug) {
console.log('> [debug] Socket disconnect')
}
init = false
reject(new Error('Socket disconnected'))
})
socket.on('error', err => {
if (debug) {
console.log('> [debug] Socket error', err.stack)
}
reject(err)
})
function onLogs(logs) {
logs.sort(compare).forEach(onLog)
}
function onLog(log) {
lastLog = log
printLog(log)
}
})
}
function printLogShort(log) {
let data
const obj = log.object
if (log.type === 'request') {
data =
`REQ "${obj.method} ${obj.uri} ${obj.protocol}"` +
` ${obj.remoteAddr} - ${obj.remoteUser || ''}` +
` "${obj.referer || ''}" "${obj.userAgent || ''}"`
} else if (log.type === 'response') {
data =
`RES "${obj.method} ${obj.uri} ${obj.protocol}"` +
` ${obj.status} ${obj.bodyBytesSent}`
} else {
data = obj
? JSON.stringify(obj, null, 2)
: (log.text || '').replace(/\n$/, '')
}
const date = dateformat(log.date, 'mm/dd hh:MM TT')
data.split('\n').forEach((line, i) => {
if (i === 0) {
console.log(`${chalk.dim(date)} ${line}`)
} else {
console.log(`${repeat(' ', date.length)} ${line}`)
}
})
}
function printLogRaw(log) {
console.log(log.object ? JSON.stringify(log.object) : log.text)
}
const logPrinters = {
short: printLogShort,
raw: printLogRaw
}
function printLog(log) {
logPrinters[outputMode](log)
}
async function fetchLogs({ token, currentTeam, since, until } = {}) {
const now = new Now({ apiUrl, token, debug, currentTeam })
let logs
try {
logs = await now.logs(deploymentIdOrURL, {
instanceId,
types,
limit,
query,
since,
until
})
} catch (err) {
handleError(err)
process.exit(1)
} finally {
now.close()
}
return logs.map(deserialize)
}
function repeat(s, n) {
return new Array(n + 1).join(s)
}
function toSerial(datestr) {
const t = Date.parse(datestr)
if (isNaN(t)) {
throw new TypeError('Invalid date string')
}
const pidLen = 19
const seqLen = 19
return t + repeat('0', pidLen + seqLen)
}