log.ts 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. cleanup(Global.Path.log)
  47. if (options.print) return
  48. logpath = path.join(
  49. Global.Path.log,
  50. options.dev ? "dev.log" : new Date().toISOString().split(".")[0].replace(/:/g, "") + ".log",
  51. )
  52. const logfile = Bun.file(logpath)
  53. await fs.truncate(logpath).catch(() => {})
  54. const writer = logfile.writer()
  55. process.stderr.write = (msg) => {
  56. writer.write(msg)
  57. writer.flush()
  58. return true
  59. }
  60. }
  61. async function cleanup(dir: string) {
  62. const glob = new Bun.Glob("????-??-??T??????.log")
  63. const files = await Array.fromAsync(
  64. glob.scan({
  65. cwd: dir,
  66. absolute: true,
  67. }),
  68. )
  69. if (files.length <= 5) return
  70. const filesToDelete = files.slice(0, -10)
  71. await Promise.all(filesToDelete.map((file) => fs.unlink(file).catch(() => {})))
  72. }
  73. function formatError(error: Error, depth = 0): string {
  74. const result = error.message
  75. return error.cause instanceof Error && depth < 10
  76. ? result + " Caused by: " + formatError(error.cause, depth + 1)
  77. : result
  78. }
  79. let last = Date.now()
  80. export function create(tags?: Record<string, any>) {
  81. tags = tags || {}
  82. const service = tags["service"]
  83. if (service && typeof service === "string") {
  84. const cached = loggers.get(service)
  85. if (cached) {
  86. return cached
  87. }
  88. }
  89. function build(message: any, extra?: Record<string, any>) {
  90. const prefix = Object.entries({
  91. ...tags,
  92. ...extra,
  93. })
  94. .filter(([_, value]) => value !== undefined && value !== null)
  95. .map(([key, value]) => {
  96. const prefix = `${key}=`
  97. if (value instanceof Error) return prefix + formatError(value)
  98. if (typeof value === "object") return prefix + JSON.stringify(value)
  99. return prefix + value
  100. })
  101. .join(" ")
  102. const next = new Date()
  103. const diff = next.getTime() - last
  104. last = next.getTime()
  105. return [next.toISOString().split(".")[0], "+" + diff + "ms", prefix, message].filter(Boolean).join(" ") + "\n"
  106. }
  107. const result: Logger = {
  108. debug(message?: any, extra?: Record<string, any>) {
  109. if (shouldLog("DEBUG")) {
  110. process.stderr.write("DEBUG " + build(message, extra))
  111. }
  112. },
  113. info(message?: any, extra?: Record<string, any>) {
  114. if (shouldLog("INFO")) {
  115. process.stderr.write("INFO " + build(message, extra))
  116. }
  117. },
  118. error(message?: any, extra?: Record<string, any>) {
  119. if (shouldLog("ERROR")) {
  120. process.stderr.write("ERROR " + build(message, extra))
  121. }
  122. },
  123. warn(message?: any, extra?: Record<string, any>) {
  124. if (shouldLog("WARN")) {
  125. process.stderr.write("WARN " + build(message, extra))
  126. }
  127. },
  128. tag(key: string, value: string) {
  129. if (tags) tags[key] = value
  130. return result
  131. },
  132. clone() {
  133. return Log.create({ ...tags })
  134. },
  135. time(message: string, extra?: Record<string, any>) {
  136. const now = Date.now()
  137. result.info(message, { status: "started", ...extra })
  138. function stop() {
  139. result.info(message, {
  140. status: "completed",
  141. duration: Date.now() - now,
  142. ...extra,
  143. })
  144. }
  145. return {
  146. stop,
  147. [Symbol.dispose]() {
  148. stop()
  149. },
  150. }
  151. },
  152. }
  153. if (service && typeof service === "string") {
  154. loggers.set(service, result)
  155. }
  156. return result
  157. }
  158. }