log.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. export * as Log from "./log"
  2. import path from "path"
  3. import fs from "fs/promises"
  4. import { createWriteStream } from "fs"
  5. import * as Global from "../global"
  6. import { Schema } from "effect"
  7. import { Glob } from "./glob"
  8. export const Level = Schema.Literals(["DEBUG", "INFO", "WARN", "ERROR"]).annotate({
  9. identifier: "LogLevel",
  10. description: "Log level",
  11. })
  12. export type Level = Schema.Schema.Type<typeof Level>
  13. const levelPriority: Record<Level, number> = {
  14. DEBUG: 0,
  15. INFO: 1,
  16. WARN: 2,
  17. ERROR: 3,
  18. }
  19. const keep = 10
  20. const initializedRunID = "OPENCODE_LOG_INITIALIZED_RUN_ID"
  21. let level: Level = "INFO"
  22. function shouldLog(input: Level): boolean {
  23. return levelPriority[input] >= levelPriority[level]
  24. }
  25. export type Logger = {
  26. debug(message?: any, extra?: Record<string, any>): void
  27. info(message?: any, extra?: Record<string, any>): void
  28. error(message?: any, extra?: Record<string, any>): void
  29. warn(message?: any, extra?: Record<string, any>): void
  30. tag(key: string, value: string): Logger
  31. clone(): Logger
  32. time(
  33. message: string,
  34. extra?: Record<string, any>,
  35. ): {
  36. stop(): void
  37. [Symbol.dispose](): void
  38. }
  39. }
  40. const loggers = new Map<string, Logger>()
  41. export const Default = create({ service: "default" })
  42. export interface Options {
  43. print: boolean
  44. dev?: boolean
  45. level?: Level
  46. }
  47. let logpath = ""
  48. export function file() {
  49. return logpath
  50. }
  51. let write = (msg: any) => {
  52. process.stderr.write(msg)
  53. return msg.length
  54. }
  55. export async function init(options: Options) {
  56. if (options.level) level = options.level
  57. void cleanup(Global.Path.log)
  58. if (options.print) return
  59. logpath = path.join(
  60. Global.Path.log,
  61. options.dev ? "dev.log" : new Date().toISOString().split(".")[0].replace(/:/g, "") + ".log",
  62. )
  63. const runID = process.env.OPENCODE_RUN_ID
  64. const shouldTruncate = !options.dev || !runID || process.env[initializedRunID] !== runID
  65. if (shouldTruncate) await fs.truncate(logpath).catch(() => {})
  66. if (options.dev && runID) process.env[initializedRunID] = runID
  67. const stream = createWriteStream(logpath, { flags: "a" })
  68. write = async (msg: any) => {
  69. return new Promise((resolve, reject) => {
  70. stream.write(msg, (err) => {
  71. if (err) reject(err)
  72. else resolve(msg.length)
  73. })
  74. })
  75. }
  76. }
  77. async function cleanup(dir: string) {
  78. const files = (
  79. await Glob.scan("????-??-??T??????.log", {
  80. cwd: dir,
  81. absolute: false,
  82. include: "file",
  83. }).catch(() => [])
  84. )
  85. .filter((file) => path.basename(file) === file)
  86. .sort()
  87. if (files.length <= keep) return
  88. const doomed = files.slice(0, -keep)
  89. await Promise.all(doomed.map((file) => fs.unlink(path.join(dir, file)).catch(() => {})))
  90. }
  91. function formatError(error: Error, depth = 0): string {
  92. const result = error.message
  93. return error.cause instanceof Error && depth < 10
  94. ? result + " Caused by: " + formatError(error.cause, depth + 1)
  95. : result
  96. }
  97. let last = Date.now()
  98. export function create(tags?: Record<string, any>) {
  99. tags = tags || {}
  100. const service = tags["service"]
  101. if (service && typeof service === "string") {
  102. const cached = loggers.get(service)
  103. if (cached) {
  104. return cached
  105. }
  106. }
  107. function build(message: any, extra?: Record<string, any>) {
  108. const prefix = Object.entries({
  109. ...tags,
  110. ...extra,
  111. })
  112. .filter(([_, value]) => value !== undefined && value !== null)
  113. .map(([key, value]) => {
  114. const prefix = `${key}=`
  115. if (value instanceof Error) return prefix + formatError(value)
  116. if (typeof value === "object") return prefix + JSON.stringify(value)
  117. return prefix + value
  118. })
  119. .join(" ")
  120. const next = new Date()
  121. const diff = next.getTime() - last
  122. last = next.getTime()
  123. return [next.toISOString().split(".")[0], "+" + diff + "ms", prefix, message].filter(Boolean).join(" ") + "\n"
  124. }
  125. const result: Logger = {
  126. debug(message?: any, extra?: Record<string, any>) {
  127. if (shouldLog("DEBUG")) {
  128. write("DEBUG " + build(message, extra))
  129. }
  130. },
  131. info(message?: any, extra?: Record<string, any>) {
  132. if (shouldLog("INFO")) {
  133. write("INFO " + build(message, extra))
  134. }
  135. },
  136. error(message?: any, extra?: Record<string, any>) {
  137. if (shouldLog("ERROR")) {
  138. write("ERROR " + build(message, extra))
  139. }
  140. },
  141. warn(message?: any, extra?: Record<string, any>) {
  142. if (shouldLog("WARN")) {
  143. write("WARN " + build(message, extra))
  144. }
  145. },
  146. tag(key: string, value: string) {
  147. if (tags) tags[key] = value
  148. return result
  149. },
  150. clone() {
  151. return create({ ...tags })
  152. },
  153. time(message: string, extra?: Record<string, any>) {
  154. const now = Date.now()
  155. result.info(message, { status: "started", ...extra })
  156. function stop() {
  157. result.info(message, {
  158. status: "completed",
  159. duration: Date.now() - now,
  160. ...extra,
  161. })
  162. }
  163. return {
  164. stop,
  165. [Symbol.dispose]() {
  166. stop()
  167. },
  168. }
  169. },
  170. }
  171. if (service && typeof service === "string") {
  172. loggers.set(service, result)
  173. }
  174. return result
  175. }