From 645f40ce7a5b6f78bce658eb2ded1012d846b224 Mon Sep 17 00:00:00 2001 From: Roberto Morado Date: Fri, 15 May 2026 23:32:03 -0400 Subject: [PATCH] Logger --- .gitignore | 2 ++ deno.json | 4 ++-- main.ts | 1 + src/logger.ts | 42 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 .gitignore create mode 100644 src/logger.ts diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7a6501a --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.env +logs/ diff --git a/deno.json b/deno.json index f3e6d30..6ca594e 100644 --- a/deno.json +++ b/deno.json @@ -1,7 +1,7 @@ { "tasks": { - "dev": "deno run --allow-net --allow-env --allow-read --env-file --unstable-kv main.ts", - "start": "deno run --allow-net --allow-env --allow-read --env-file --unstable-kv main.ts" + "dev": "deno run --allow-net --allow-env --allow-read --allow-write --env-file --unstable-kv main.ts", + "start": "deno run --allow-net --allow-env --allow-read --allow-write --env-file --unstable-kv main.ts" }, "imports": { "hono": "npm:hono@^4", diff --git a/main.ts b/main.ts index e1f6984..5ca740d 100644 --- a/main.ts +++ b/main.ts @@ -1,3 +1,4 @@ +import "./src/logger.ts"; import { Hono } from "hono"; import { logger } from "hono/logger"; import { session } from "./src/middleware/session.ts"; diff --git a/src/logger.ts b/src/logger.ts new file mode 100644 index 0000000..34609f6 --- /dev/null +++ b/src/logger.ts @@ -0,0 +1,42 @@ +// Patches global console so every log/warn/error is written to logs/YYYY-MM-DD.log +// Import once at the top of main.ts — no other changes needed anywhere. + +const LOG_DIR = "./logs"; + +try { + Deno.mkdirSync(LOG_DIR, { recursive: true }); +} catch { /* already exists */ } + +const enc = new TextEncoder(); +let currentDate = ""; +let file: Deno.FsFile | null = null; + +function getFile(): Deno.FsFile { + const today = new Date().toISOString().slice(0, 10); // YYYY-MM-DD + if (today !== currentDate) { + file?.close(); + file = Deno.openSync(`${LOG_DIR}/${today}.log`, { create: true, append: true }); + currentDate = today; + } + return file!; +} + +function write(level: string, args: unknown[]) { + const ts = new Date().toISOString(); + const body = args + .map((a) => (typeof a === "string" ? a : JSON.stringify(a, null, 2))) + .join(" "); + try { + getFile().writeSync(enc.encode(`[${ts}] [${level}] ${body}\n`)); + } catch { /* don't let a log failure crash the app */ } +} + +const _log = console.log.bind(console); +const _info = console.info.bind(console); +const _warn = console.warn.bind(console); +const _error = console.error.bind(console); + +console.log = (...a: unknown[]) => { _log(...a); write("INFO", a); }; +console.info = (...a: unknown[]) => { _info(...a); write("INFO", a); }; +console.warn = (...a: unknown[]) => { _warn(...a); write("WARN", a); }; +console.error = (...a: unknown[]) => { _error(...a); write("ERROR", a); }; -- 2.39.5