1 import { registerTSPaths } from '../server/helpers/register-ts-paths'
4 import * as program from 'commander'
5 import { createReadStream, readdir } from 'fs-extra'
6 import { join } from 'path'
7 import { createInterface } from 'readline'
8 import * as winston from 'winston'
9 import { labelFormatter } from '../server/helpers/logger'
10 import { CONFIG } from '../server/initializers/config'
11 import { mtimeSortFilesDesc } from '../shared/core-utils/logs/logs'
12 import { inspect } from 'util'
13 import { format as sqlFormat } from 'sql-formatter'
16 .option('-l, --level [level]', 'Level log (debug/info/warn/error)')
17 .option('-f, --files [file...]', 'Files to parse. If not provided, the script will parse the latest log file from config)')
20 const options = program.opts()
22 const excludedKeys = {
30 function keysExcluder (key, value) {
31 return excludedKeys[key] === true ? undefined : value
34 const loggerFormat = winston.format.printf((info) => {
35 let additionalInfos = JSON.stringify(info, keysExcluder, 2)
36 if (additionalInfos === '{}') additionalInfos = ''
37 else additionalInfos = ' ' + additionalInfos
40 if (CONFIG.LOG.PRETTIFY_SQL) {
41 additionalInfos += '\n' + sqlFormat(info.sql, {
46 additionalInfos += ' - ' + info.sql
50 return `[${info.label}] ${toTimeFormat(info.timestamp)} ${info.level}: ${info.message}${additionalInfos}`
53 const logger = winston.createLogger({
55 new winston.transports.Console({
56 level: options.level || 'debug',
58 format: winston.format.combine(
59 winston.format.splat(),
61 winston.format.colorize(),
70 error: logger.error.bind(logger),
71 warn: logger.warn.bind(logger),
72 info: logger.info.bind(logger),
73 debug: logger.debug.bind(logger)
77 .then(() => process.exit(0))
78 .catch(err => console.error(err))
81 return new Promise<void>(async res => {
82 const files = await getFiles()
84 for (const file of files) {
85 console.log('Opening %s.', file)
87 const stream = createReadStream(file)
89 const rl = createInterface({
93 rl.on('line', line => {
95 const log = JSON.parse(line)
96 // Don't know why but loggerFormat does not remove splat key
97 Object.assign(log, { splat: undefined })
99 logLevels[log.level](log)
101 console.error('Cannot parse line.', inspect(line))
106 stream.once('close', () => res())
111 // Thanks: https://stackoverflow.com/a/37014317
112 async function getNewestFile (files: string[], basePath: string) {
113 const sorted = await mtimeSortFilesDesc(files, basePath)
115 return (sorted.length > 0) ? sorted[0].file : ''
118 async function getFiles () {
119 if (options.files) return options.files
121 const logFiles = await readdir(CONFIG.STORAGE.LOG_DIR)
123 const filename = await getNewestFile(logFiles, CONFIG.STORAGE.LOG_DIR)
124 return [ join(CONFIG.STORAGE.LOG_DIR, filename) ]
127 function toTimeFormat (time: string) {
128 const timestamp = Date.parse(time)
130 if (isNaN(timestamp) === true) return 'Unknown date'
132 return new Date(timestamp).toISOString()