memorium/lib/cache/logs.ts

38 lines
940 B
TypeScript
Raw Normal View History

2023-08-13 02:26:22 +02:00
import { createLogger } from "@lib/log.ts";
import * as cache from "@lib/cache/cache.ts";
import { getTimeCacheKey, parseTimeCacheKey } from "@lib/string.ts";
const log = createLogger("");
log.addEventListener("log", (data) => {
cache.set(`log:${getTimeCacheKey()}`, JSON.stringify(data.detail), {
noLog: true,
});
});
export type Log = {
scope: string;
level: number;
date: Date;
args: unknown[];
};
export async function getLogs() {
const d = new Date();
const year = d.getFullYear();
const month = d.getMonth().toString();
const day = d.getDate().toString();
2023-08-13 02:26:22 +02:00
const keys = await cache.keys(
`log:${year}:${month}:${day}:*`,
);
const logs = await Promise.all(
keys.map(async (key) => {
const date = parseTimeCacheKey(key);
return { ...JSON.parse(await cache.get<string>(key)), date } as Log;
}),
);
return logs.sort((a, b) => a.date.getTime() > b.date.getTime() ? -1 : 1);
}