log.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import path from "path"
  2. import fs from "fs/promises"
  3. import { Global } from "../global"
  4. import z from "zod"
  5. export namespace Log {
  6. export const Level = z.enum(["DEBUG", "INFO", "WARN", "ERROR"]).openapi({ ref: "LogLevel", description: "Log level" })
  7. export type Level = z.infer<typeof Level>
  8. const levelPriority: Record<Level, number> = {
  9. DEBUG: 0,
  10. INFO: 1,
  11. WARN: 2,
  12. ERROR: 3,
  13. }
  14. let level: Level = "INFO"
  15. function shouldLog(input: Level): boolean {
  16. return levelPriority[input] >= levelPriority[level]
  17. }
  18. export type Logger = {
  19. debug(message?: any, extra?: Record<string, any>): void
  20. info(message?: any, extra?: Record<string, any>): void
  21. error(message?: any, extra?: Record<string, any>): void
  22. warn(message?: any, extra?: Record<string, any>): void
  23. tag(key: string, value: string): Logger
  24. clone(): Logger
  25. time(
  26. message: string,
  27. extra?: Record<string, any>,
  28. ): {
  29. stop(): void
  30. [Symbol.dispose](): void
  31. }
  32. }
  33. const loggers = new Map<string, Logger>()
  34. export const Default = create({ service: "default" })
  35. export interface Options {
  36. print: boolean
  37. dev?: boolean
  38. level?: Level
  39. }
  40. let logpath = ""
  41. export function file() {
  42. return logpath
  43. }
  44. export async function init(options: Options) {
  45. if (options.level) level = options.level
  46. const dir = path.join(Global.Path.data, "log")
  47. await fs.mkdir(dir, { recursive: true })
  48. cleanup(dir)
  49. if (options.print) return
  50. logpath = path.join(
  51. dir,
  52. options.dev ? "dev.log" : new Date().toISOString().split(".")[0].replace(/:/g, "") + ".log",
  53. )
  54. const logfile = Bun.file(logpath)
  55. await fs.truncate(logpath).catch(() => {})
  56. const writer = logfile.writer()
  57. process.stderr.write = (msg) => {
  58. writer.write(msg)
  59. writer.flush()
  60. return true
  61. }
  62. }
  63. async function cleanup(dir: string) {
  64. const glob = new Bun.Glob("????-??-??T??????.log")
  65. const files = await Array.fromAsync(
  66. glob.scan({
  67. cwd: dir,
  68. absolute: true,
  69. }),
  70. )
  71. if (files.length <= 5) return
  72. const filesToDelete = files.slice(0, -10)
  73. await Promise.all(filesToDelete.map((file) => fs.unlink(file).catch(() => {})))
  74. }
  75. let last = Date.now()
  76. export function create(tags?: Record<string, any>) {
  77. tags = tags || {}
  78. const service = tags["service"]
  79. if (service && typeof service === "string") {
  80. const cached = loggers.get(service)
  81. if (cached) {
  82. return cached
  83. }
  84. }
  85. function build(message: any, extra?: Record<string, any>) {
  86. const prefix = Object.entries({
  87. ...tags,
  88. ...extra,
  89. })
  90. .filter(([_, value]) => value !== undefined && value !== null)
  91. .map(([key, value]) => `${key}=${typeof value === "object" ? JSON.stringify(value) : value}`)
  92. .join(" ")
  93. const next = new Date()
  94. const diff = next.getTime() - last
  95. last = next.getTime()
  96. return [next.toISOString().split(".")[0], "+" + diff + "ms", prefix, message].filter(Boolean).join(" ") + "\n"
  97. }
  98. const result: Logger = {
  99. debug(message?: any, extra?: Record<string, any>) {
  100. if (shouldLog("DEBUG")) {
  101. process.stderr.write("DEBUG " + build(message, extra))
  102. }
  103. },
  104. info(message?: any, extra?: Record<string, any>) {
  105. if (shouldLog("INFO")) {
  106. process.stderr.write("INFO " + build(message, extra))
  107. }
  108. },
  109. error(message?: any, extra?: Record<string, any>) {
  110. if (shouldLog("ERROR")) {
  111. process.stderr.write("ERROR " + build(message, extra))
  112. }
  113. },
  114. warn(message?: any, extra?: Record<string, any>) {
  115. if (shouldLog("WARN")) {
  116. process.stderr.write("WARN " + build(message, extra))
  117. }
  118. },
  119. tag(key: string, value: string) {
  120. if (tags) tags[key] = value
  121. return result
  122. },
  123. clone() {
  124. return Log.create({ ...tags })
  125. },
  126. time(message: string, extra?: Record<string, any>) {
  127. const now = Date.now()
  128. result.info(message, { status: "started", ...extra })
  129. function stop() {
  130. result.info(message, {
  131. status: "completed",
  132. duration: Date.now() - now,
  133. ...extra,
  134. })
  135. }
  136. return {
  137. stop,
  138. [Symbol.dispose]() {
  139. stop()
  140. },
  141. }
  142. },
  143. }
  144. if (service && typeof service === "string") {
  145. loggers.set(service, result)
  146. }
  147. return result
  148. }
  149. }