]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - scripts/parse-log.ts
Increase test timeout for imports
[github/Chocobozzz/PeerTube.git] / scripts / parse-log.ts
1 import * as program from 'commander'
2 import { createReadStream, readdirSync, statSync } from 'fs'
3 import { join } from 'path'
4 import { createInterface } from 'readline'
5 import * as winston from 'winston'
6 import { labelFormatter } from '../server/helpers/logger'
7 import { CONFIG } from '../server/initializers/constants'
8
9 program
10 .option('-l, --level [level]', 'Level log (debug/info/warn/error)')
11 .parse(process.argv)
12
13 const excludedKeys = {
14 level: true,
15 message: true,
16 splat: true,
17 timestamp: true,
18 label: true
19 }
20 function keysExcluder (key, value) {
21 return excludedKeys[key] === true ? undefined : value
22 }
23
24 const loggerFormat = winston.format.printf((info) => {
25 let additionalInfos = JSON.stringify(info, keysExcluder, 2)
26 if (additionalInfos === '{}') additionalInfos = ''
27 else additionalInfos = ' ' + additionalInfos
28
29 return `[${info.label}] ${toTimeFormat(info.timestamp)} ${info.level}: ${info.message}${additionalInfos}`
30 })
31
32 const logger = winston.createLogger({
33 transports: [
34 new winston.transports.Console({
35 level: program['level'] || 'debug',
36 stderrLevels: [],
37 format: winston.format.combine(
38 winston.format.splat(),
39 labelFormatter,
40 winston.format.colorize(),
41 loggerFormat
42 )
43 })
44 ],
45 exitOnError: true
46 })
47
48 const logLevels = {
49 error: logger.error.bind(logger),
50 warn: logger.warn.bind(logger),
51 info: logger.info.bind(logger),
52 debug: logger.debug.bind(logger)
53 }
54
55 const logFiles = readdirSync(CONFIG.STORAGE.LOG_DIR)
56 const lastLogFile = getNewestFile(logFiles, CONFIG.STORAGE.LOG_DIR)
57
58 const path = join(CONFIG.STORAGE.LOG_DIR, lastLogFile)
59 console.log('Opening %s.', path)
60
61 const rl = createInterface({
62 input: createReadStream(path)
63 })
64
65 rl.on('line', line => {
66 const log = JSON.parse(line)
67 // Don't know why but loggerFormat does not remove splat key
68 Object.assign(log, { splat: undefined })
69
70 logLevels[log.level](log)
71 })
72
73 function toTimeFormat (time: string) {
74 const timestamp = Date.parse(time)
75
76 if (isNaN(timestamp) === true) return 'Unknown date'
77
78 return new Date(timestamp).toISOString()
79 }
80
81 // Thanks: https://stackoverflow.com/a/37014317
82 function getNewestFile (files: string[], basePath: string) {
83 const out = []
84
85 files.forEach(file => {
86 const stats = statSync(basePath + '/' + file)
87 if (stats.isFile()) out.push({ file, mtime: stats.mtime.getTime() })
88 })
89
90 out.sort((a, b) => b.mtime - a.mtime)
91
92 return (out.length > 0) ? out[ 0 ].file : ''
93 }