cloudaxe-opencode/packages/opencode/src/util/log.ts

174 lines
4.6 KiB
TypeScript
Raw Normal View History

2025-05-31 18:41:00 +00:00
import path from "path"
import fs from "fs/promises"
import { Global } from "../global"
2025-07-09 15:00:03 +00:00
import z from "zod"
2025-05-18 01:31:42 +00:00
export namespace Log {
2025-07-09 15:00:03 +00:00
export const Level = z.enum(["DEBUG", "INFO", "WARN", "ERROR"]).openapi({ ref: "LogLevel", description: "Log level" })
export type Level = z.infer<typeof Level>
const levelPriority: Record<Level, number> = {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3,
}
let currentLevel: Level = "INFO"
export function setLevel(level: Level) {
currentLevel = level
}
export function getLevel(): Level {
return currentLevel
}
function shouldLog(level: Level): boolean {
return levelPriority[level] >= levelPriority[currentLevel]
}
2025-07-09 13:16:10 +00:00
export type Logger = {
2025-07-09 15:00:03 +00:00
debug(message?: any, extra?: Record<string, any>): void
2025-07-09 13:16:10 +00:00
info(message?: any, extra?: Record<string, any>): void
error(message?: any, extra?: Record<string, any>): void
warn(message?: any, extra?: Record<string, any>): void
tag(key: string, value: string): Logger
clone(): Logger
time(
message: string,
extra?: Record<string, any>,
): {
stop(): void
[Symbol.dispose](): void
}
}
const loggers = new Map<string, Logger>()
export const Default = create({ service: "default" })
2025-06-09 19:00:48 +00:00
export interface Options {
print: boolean
dev?: boolean
2025-07-09 15:00:03 +00:00
level?: Level
2025-05-31 18:41:00 +00:00
}
2025-05-18 18:28:08 +00:00
2025-06-09 19:00:48 +00:00
let logpath = ""
export function file() {
return logpath
}
export async function init(options: Options) {
const dir = path.join(Global.Path.data, "log")
await fs.mkdir(dir, { recursive: true })
cleanup(dir)
if (options.print) return
logpath = path.join(
dir,
options.dev ? "dev.log" : new Date().toISOString().split(".")[0].replace(/:/g, "") + ".log",
)
const logfile = Bun.file(logpath)
await fs.truncate(logpath).catch(() => {})
const writer = logfile.writer()
process.stderr.write = (msg) => {
writer.write(msg)
writer.flush()
return true
2025-05-31 18:41:00 +00:00
}
2025-05-18 18:28:08 +00:00
}
async function cleanup(dir: string) {
const glob = new Bun.Glob("????-??-??T??????.log")
const files = await Array.fromAsync(
glob.scan({
cwd: dir,
absolute: true,
}),
)
2025-06-11 22:19:15 +00:00
if (files.length <= 5) return
const filesToDelete = files.slice(0, -10)
await Promise.all(filesToDelete.map((file) => fs.unlink(file).catch(() => {})))
}
let last = Date.now()
2025-05-18 01:31:42 +00:00
export function create(tags?: Record<string, any>) {
2025-05-31 18:41:00 +00:00
tags = tags || {}
2025-05-18 01:31:42 +00:00
2025-07-09 13:16:10 +00:00
const service = tags["service"]
if (service && typeof service === "string") {
const cached = loggers.get(service)
if (cached) {
return cached
}
}
2025-05-18 18:13:04 +00:00
function build(message: any, extra?: Record<string, any>) {
const prefix = Object.entries({
...tags,
...extra,
})
2025-05-30 20:39:45 +00:00
.filter(([_, value]) => value !== undefined && value !== null)
.map(([key, value]) => `${key}=${typeof value === "object" ? JSON.stringify(value) : value}`)
2025-05-31 18:41:00 +00:00
.join(" ")
const next = new Date()
const diff = next.getTime() - last
last = next.getTime()
return [next.toISOString().split(".")[0], "+" + diff + "ms", prefix, message].filter(Boolean).join(" ") + "\n"
2025-05-18 18:13:04 +00:00
}
2025-07-09 13:16:10 +00:00
const result: Logger = {
2025-07-09 15:00:03 +00:00
debug(message?: any, extra?: Record<string, any>) {
if (shouldLog("DEBUG")) {
process.stderr.write("DEBUG " + build(message, extra))
}
},
2025-05-18 01:31:42 +00:00
info(message?: any, extra?: Record<string, any>) {
2025-07-09 15:00:03 +00:00
if (shouldLog("INFO")) {
process.stderr.write("INFO " + build(message, extra))
}
2025-05-18 18:13:04 +00:00
},
error(message?: any, extra?: Record<string, any>) {
2025-07-09 15:00:03 +00:00
if (shouldLog("ERROR")) {
process.stderr.write("ERROR " + build(message, extra))
}
2025-05-18 01:31:42 +00:00
},
2025-05-31 22:42:43 +00:00
warn(message?: any, extra?: Record<string, any>) {
2025-07-09 15:00:03 +00:00
if (shouldLog("WARN")) {
process.stderr.write("WARN " + build(message, extra))
}
2025-05-31 22:42:43 +00:00
},
2025-05-18 01:31:42 +00:00
tag(key: string, value: string) {
2025-05-31 18:41:00 +00:00
if (tags) tags[key] = value
return result
2025-05-18 01:31:42 +00:00
},
clone() {
2025-05-31 18:41:00 +00:00
return Log.create({ ...tags })
2025-05-18 01:31:42 +00:00
},
2025-06-15 17:33:24 +00:00
time(message: string, extra?: Record<string, any>) {
const now = Date.now()
result.info(message, { status: "started", ...extra })
function stop() {
result.info(message, {
status: "completed",
duration: Date.now() - now,
...extra,
})
}
return {
stop,
[Symbol.dispose]() {
stop()
},
}
},
2025-05-31 18:41:00 +00:00
}
2025-05-18 01:31:42 +00:00
2025-07-09 13:16:10 +00:00
if (service && typeof service === "string") {
loggers.set(service, result)
}
2025-05-31 18:41:00 +00:00
return result
2025-05-18 01:31:42 +00:00
}
}