feat(xo-server/logs-cli): add --delete command

This commit is contained in:
Julien Fontanet 2020-07-01 18:02:17 +02:00
parent 5c901d7c1e
commit 1d0cea8ad0

View File

@ -13,6 +13,58 @@ import globMatcher from './glob-matcher'
// ===================================================================
const getLogs = (db, args) => {
let stream = highland(db.createReadStream({ reverse: true }))
if (args.since) {
stream = stream.filter(({ value }) => value.time >= args.since)
}
if (args.until) {
stream = stream.filter(({ value }) => value.time <= args.until)
}
const fields = Object.keys(args.matchers)
if (fields.length > 0) {
stream = stream.filter(({ value }) => {
for (const field of fields) {
const fieldValue = get(value, field)
if (fieldValue === undefined || !args.matchers[field](fieldValue)) {
return false
}
}
return true
})
}
return stream.take(args.limit)
}
// ===================================================================
const deleteLogs = (db, args) =>
new Promise(resolve => {
let count = 1
const cb = () => {
if (--count === 0) {
resolve()
}
}
const deleteEntry = key => {
++count
db.del(key, cb)
}
getLogs(db, args)
.each(({ key }) => {
deleteEntry(key)
})
.done(cb)
})
const GC_KEEP = 2e4
const gc = (db, args) =>
@ -64,32 +116,7 @@ const gc = (db, args) =>
})
async function printLogs(db, args) {
let stream = highland(db.createReadStream({ reverse: true }))
if (args.since) {
stream = stream.filter(({ value }) => value.time >= args.since)
}
if (args.until) {
stream = stream.filter(({ value }) => value.time <= args.until)
}
const fields = Object.keys(args.matchers)
if (fields.length > 0) {
stream = stream.filter(({ value }) => {
for (const field of fields) {
const fieldValue = get(value, field)
if (fieldValue === undefined || !args.matchers[field](fieldValue)) {
return false
}
}
return true
})
}
stream = stream.take(args.limit)
let stream = getLogs(db, args)
if (args.json) {
stream = highland(stream.pipe(ndjson.serialize())).each(value => {
@ -140,6 +167,12 @@ xo-server-logs --gc
Remove all but the ${GC_KEEP}th most recent log entries.
xo-server-logs --delete <predicate>...
Delete all logs matching the passed predicates.
For more information on predicates, see the print usage.
xo-server-logs --repair
Repair/compact the database.
@ -154,7 +187,7 @@ function getArgs() {
const stringArgs = ['since', 'until', 'limit']
const args = parseArgs(process.argv.slice(2), {
string: stringArgs,
boolean: ['help', 'json', 'gc', 'repair'],
boolean: ['delete', 'help', 'json', 'gc', 'repair'],
default: {
limit: 100,
json: false,
@ -258,5 +291,9 @@ export default async function main() {
}
)
return args.gc ? gc(db) : printLogs(db, args)
return args.delete
? deleteLogs(db, args)
: args.gc
? gc(db)
: printLogs(db, args)
}