Add logs endpoint

This commit is contained in:
Chocobozzz 2019-04-10 15:26:33 +02:00
parent 31b6ddf866
commit fd8710b897
No known key found for this signature in database
GPG key ID: 583A612D890159BE
24 changed files with 437 additions and 79 deletions

View file

@ -1,10 +1,11 @@
import * as program from 'commander'
import { createReadStream, readdirSync, statSync } from 'fs-extra'
import { createReadStream, readdir } from 'fs-extra'
import { join } from 'path'
import { createInterface } from 'readline'
import * as winston from 'winston'
import { labelFormatter } from '../server/helpers/logger'
import { CONFIG } from '../server/initializers/constants'
import { mtimeSortFilesDesc } from '../shared/utils/logs/logs'
program
.option('-l, --level [level]', 'Level log (debug/info/warn/error)')
@ -52,23 +53,42 @@ const logLevels = {
debug: logger.debug.bind(logger)
}
const logFiles = readdirSync(CONFIG.STORAGE.LOG_DIR)
const lastLogFile = getNewestFile(logFiles, CONFIG.STORAGE.LOG_DIR)
run()
.then(() => process.exit(0))
.catch(err => console.error(err))
const path = join(CONFIG.STORAGE.LOG_DIR, lastLogFile)
console.log('Opening %s.', path)
function run () {
return new Promise(async res => {
const logFiles = await readdir(CONFIG.STORAGE.LOG_DIR)
const lastLogFile = await getNewestFile(logFiles, CONFIG.STORAGE.LOG_DIR)
const rl = createInterface({
input: createReadStream(path)
})
const path = join(CONFIG.STORAGE.LOG_DIR, lastLogFile)
console.log('Opening %s.', path)
rl.on('line', line => {
const log = JSON.parse(line)
// Don't know why but loggerFormat does not remove splat key
Object.assign(log, { splat: undefined })
const stream = createReadStream(path)
logLevels[log.level](log)
})
const rl = createInterface({
input: stream
})
rl.on('line', line => {
const log = JSON.parse(line)
// Don't know why but loggerFormat does not remove splat key
Object.assign(log, { splat: undefined })
logLevels[ log.level ](log)
})
stream.once('close', () => res())
})
}
// Thanks: https://stackoverflow.com/a/37014317
async function getNewestFile (files: string[], basePath: string) {
const sorted = await mtimeSortFilesDesc(files, basePath)
return (sorted.length > 0) ? sorted[ 0 ].file : ''
}
function toTimeFormat (time: string) {
const timestamp = Date.parse(time)
@ -77,17 +97,3 @@ function toTimeFormat (time: string) {
return new Date(timestamp).toISOString()
}
// Thanks: https://stackoverflow.com/a/37014317
function getNewestFile (files: string[], basePath: string) {
const out = []
files.forEach(file => {
const stats = statSync(basePath + '/' + file)
if (stats.isFile()) out.push({ file, mtime: stats.mtime.getTime() })
})
out.sort((a, b) => b.mtime - a.mtime)
return (out.length > 0) ? out[ 0 ].file : ''
}