-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.ts
More file actions
87 lines (71 loc) · 2.18 KB
/
Copy pathlogger.ts
File metadata and controls
87 lines (71 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { redact, redactString } from "./redaction.js";
export type LogLevel = "debug" | "info" | "warn" | "error";
const LEVEL_ORDER: Record<LogLevel, number> = {
debug: 10,
info: 20,
warn: 30,
error: 40,
};
function getGlobalDir(): string {
return process.env.PROMPT_REFINER_GLOBAL_DIR || path.join(os.homedir(), ".refiner");
}
function getRuntimeLogPath(): string {
return path.join(getGlobalDir(), "runtime.log");
}
function getConfiguredLevel(): LogLevel {
const value = (process.env.PROMPT_REFINER_LOG_LEVEL || "info").toLowerCase();
return value in LEVEL_ORDER ? (value as LogLevel) : "info";
}
function shouldLog(level: LogLevel): boolean {
return LEVEL_ORDER[level] >= LEVEL_ORDER[getConfiguredLevel()];
}
function serializeMeta(meta?: unknown): string {
if (meta === undefined) {
return "";
}
const safeMeta = redact(meta);
try {
return typeof safeMeta === "string" ? safeMeta : JSON.stringify(safeMeta);
} catch {
return redactString(String(safeMeta));
}
}
function write(level: LogLevel, message: string, meta?: unknown) {
const timestamp = new Date().toISOString();
const renderedMeta = serializeMeta(meta);
const line = `[${timestamp}] [${level.toUpperCase()}] ${redactString(message)}${renderedMeta ? ` | ${renderedMeta}` : ""}`;
try {
fs.mkdirSync(getGlobalDir(), { recursive: true });
fs.appendFileSync(getRuntimeLogPath(), line + os.EOL, "utf-8");
} catch {
}
if (level === "error" || level === "warn") {
console.error(line);
} else {
// We avoid console.log to prevent polluting stdout, which is reserved for JSON-RPC
console.error(line);
}
}
export class RuntimeLogger {
static debug(message: string, meta?: unknown) {
if (shouldLog("debug")) {
write("debug", message, meta);
}
}
static info(message: string, meta?: unknown) {
if (shouldLog("info")) {
write("info", message, meta);
}
}
static warn(message: string, meta?: unknown) {
if (shouldLog("warn")) {
write("warn", message, meta);
}
}
static error(message: string, meta?: unknown) {
write("error", message, meta);
}
}