logging.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { Formatter, Logger, type LogLevel } from "effect"
  2. import path from "path"
  3. import { Global } from "../global"
  4. import { runID } from "./shared"
  5. function formatter(id: string = runID) {
  6. return Logger.map(Logger.formatStructured, (output) => {
  7. const messages = Array.isArray(output.message) ? output.message : [output.message]
  8. return [
  9. ["timestamp", output.timestamp],
  10. ["level", output.level],
  11. ["run", id],
  12. ...messages.flatMap((value) => (plain(value) ? flatten(value) : [["message", value] as const])),
  13. ...(output.cause === undefined ? [] : [["cause", output.cause] as const]),
  14. ...flatten(output.spans),
  15. ...flatten(output.annotations),
  16. ]
  17. .map(([key, value]) => `${key}=${format(value)}`)
  18. .join(" ")
  19. })
  20. }
  21. function flatten(
  22. input: Record<string, unknown>,
  23. prefix = "",
  24. seen = new WeakSet<object>(),
  25. ): Array<readonly [string, unknown]> {
  26. if (seen.has(input)) return [[prefix, "[Circular]"]]
  27. seen.add(input)
  28. const entries = Object.entries(input)
  29. if (entries.length === 0 && prefix) return [[prefix, input]]
  30. return entries.flatMap(([key, value]) => {
  31. const path = prefix ? `${prefix}.${key}` : key
  32. return plain(value) ? flatten(value, path, seen) : [[path, value] as const]
  33. })
  34. }
  35. function plain(input: unknown): input is Record<string, unknown> {
  36. if (input === null || typeof input !== "object" || Array.isArray(input)) return false
  37. const prototype = Object.getPrototypeOf(input)
  38. return prototype === Object.prototype || prototype === null
  39. }
  40. function format(input: unknown) {
  41. const value = typeof input === "string" ? input : Formatter.format(input)
  42. return /^[^\s="\\]+$/.test(value) ? value : JSON.stringify(value)
  43. }
  44. export function fileLogger(file = path.join(Global.Path.log, "opencode.log"), id: string = runID) {
  45. return Logger.toFile(formatter(id), file, { flag: "a", batchWindow: 0 })
  46. }
  47. const stderrLogger = Logger.make((options) => process.stderr.write(formatter().log(options) + "\n"))
  48. export function minimumLogLevel() {
  49. const value = process.env.OPENCODE_LOG_LEVEL?.toUpperCase()
  50. const levels = {
  51. DEBUG: "Debug",
  52. INFO: "Info",
  53. WARN: "Warn",
  54. ERROR: "Error",
  55. } as const satisfies Record<string, LogLevel.LogLevel>
  56. return value && value in levels ? levels[value as keyof typeof levels] : levels.INFO
  57. }
  58. export function loggers() {
  59. return process.env.OPENCODE_PRINT_LOGS === "1" ? [fileLogger(), stderrLogger] : [fileLogger()]
  60. }
  61. export * as Logging from "./logging"