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