Parent directory

log.ts

951 bytes
 1import { createWriteStream, mkdirSync, type WriteStream } from "fs";
 2import { join } from "path";
 3import { homedir } from "os";
 4
 5const LOG_DIR = join(homedir(), ".local", "share", "opencode-telegram", "log");
 6
 7let stream: WriteStream;
 8
 9function getStream(): WriteStream {
10  if (!stream) {
11    mkdirSync(LOG_DIR, { recursive: true });
12    const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
13    stream = createWriteStream(join(LOG_DIR, `${timestamp}.log`), {
14      flags: "a",
15    });
16  }
17  return stream;
18}
19
20function write(level: string, msg: string): void {
21  const ts = new Date().toISOString();
22  getStream().write(`${ts} ${level} ${msg}\n`);
23}
24
25export function info(msg: string): void {
26  write("INFO", msg);
27}
28
29export function error(msg: string, err?: unknown): void {
30  const suffix =
31    err !== undefined
32      ? ` ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`
33      : "";
34  write("ERROR", msg + suffix);
35}