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

177 lines
4.8 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"
import z from "zod"
2025-07-09 15:00:03 +00:00
2025-05-18 01:31:42 +00:00
export namespace Log {
export const Level = z.enum(["DEBUG", "INFO", "WARN", "ERROR"]).meta({ ref: "LogLevel", description: "Log level" })
2025-07-09 15:00:03 +00:00
export type Level = z.infer<typeof Level>
const levelPriority: Record<Level, number> = {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3,
}
2025-07-19 17:35:42 +00:00
let level: Level = "INFO"
2025-07-09 15:00:03 +00:00
2025-07-19 17:35:42 +00:00
function shouldLog(input: Level): boolean {
return levelPriority[input] >= levelPriority[level]
2025-07-09 15:00:03 +00:00
}
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) {
2025-07-19 17:35:42 +00:00
if (options.level) level = options.level
2025-07-31 13:35:57 +00:00
cleanup(Global.Path.log)
if (options.print) return
logpath = path.join(
2025-07-31 13:35:57 +00:00
Global.Path.log,
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(() => {})))
}
2025-08-31 22:11:04 +00:00
function formatError(error: Error, depth = 0): string {
const result = error.message
return error.cause instanceof Error && depth < 10
? result + " Caused by: " + formatError(error.cause, depth + 1)
: result
}
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)
2025-08-22 04:27:49 +00:00
.map(([key, value]) => {
const prefix = `${key}=`
2025-08-31 22:11:04 +00:00
if (value instanceof Error) return prefix + formatError(value)
2025-08-22 04:27:49 +00:00
if (typeof value === "object") return prefix + JSON.stringify(value)
return prefix + 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
}
}