feat: add logging

This commit is contained in:
2023-08-13 02:26:22 +02:00
parent 59ddcb64a6
commit 830b33462d
9 changed files with 266 additions and 114 deletions

4
lib/cache/cache.ts vendored
View File

@@ -6,6 +6,7 @@ import {
RedisValue,
} from "https://deno.land/x/redis@v0.31.0/mod.ts";
import { createLogger } from "@lib/log.ts";
import { getTimeCacheKey } from "@lib/string.ts";
const REDIS_HOST = Deno.env.get("REDIS_HOST");
const REDIS_PASS = Deno.env.get("REDIS_PASS") || "";
@@ -82,6 +83,7 @@ export function expire(id: string, seconds: number) {
type RedisOptions = {
expires?: number;
noLog?: boolean;
};
export function del(key: string) {
@@ -97,7 +99,7 @@ export function set<T extends RedisValue>(
content: T,
options?: RedisOptions,
) {
log.debug("storing ", { id });
if (options?.noLog !== true) log.debug("storing ", { id });
return cache.set(id, content, { ex: options?.expires || undefined });
}

37
lib/cache/logs.ts vendored Normal file
View File

@@ -0,0 +1,37 @@
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().padStart(2, "0");
const day = d.getDate().toString().padStart(2, "0");
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);
}

View File

@@ -1,4 +1,5 @@
import * as cache from "@lib/cache/cache.ts";
import { getTimeCacheKey } from "@lib/string.ts";
export type PerformancePoint = {
path: string;
@@ -16,20 +17,14 @@ export type PerformanceRes = {
};
export const savePerformance = (url: string, milliseconds: number) => {
const d = new Date();
const year = d.getFullYear();
const month = d.getMonth().toString().padStart(2, "0");
const day = d.getDay().toString().padStart(2, "0");
const hour = d.getHours().toString().padStart(2, "0");
const minute = d.getMinutes().toString().padStart(2, "0");
const seconds = d.getSeconds().toString().padStart(2, "0");
const cacheKey = getTimeCacheKey();
const u = new URL(url);
if (u.pathname.includes("_frsh/")) return;
u.searchParams.delete("__frsh_c");
cache.set(
`performance:${year}:${month}:${day}:${hour}:${minute}:${seconds}`,
`performance:${cacheKey}`,
JSON.stringify({
path: decodeURIComponent(u.pathname),
search: u.search,