log.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import path from "path"
  2. import { AppPath } from "../app/path"
  3. import fs from "fs/promises"
  4. export namespace Log {
  5. const write = {
  6. out: (msg: string) => {
  7. process.stdout.write(msg)
  8. },
  9. err: (msg: string) => {
  10. process.stderr.write(msg)
  11. },
  12. }
  13. export async function file(directory: string) {
  14. const outPath = path.join(AppPath.data(directory), "opencode.out.log")
  15. const errPath = path.join(AppPath.data(directory), "opencode.err.log")
  16. await fs.truncate(outPath).catch(() => {})
  17. await fs.truncate(errPath).catch(() => {})
  18. const out = Bun.file(outPath)
  19. const err = Bun.file(errPath)
  20. const outWriter = out.writer()
  21. const errWriter = err.writer()
  22. write["out"] = (msg) => {
  23. outWriter.write(msg)
  24. outWriter.flush()
  25. }
  26. write["err"] = (msg) => {
  27. errWriter.write(msg)
  28. errWriter.flush()
  29. }
  30. }
  31. export function create(tags?: Record<string, any>) {
  32. tags = tags || {}
  33. function build(message: any, extra?: Record<string, any>) {
  34. const prefix = Object.entries({
  35. ...tags,
  36. ...extra,
  37. })
  38. .filter(([_, value]) => value !== undefined && value !== null)
  39. .map(([key, value]) => `${key}=${value}`)
  40. .join(" ")
  41. return (
  42. [new Date().toISOString(), prefix, message].filter(Boolean).join(" ") +
  43. "\n"
  44. )
  45. }
  46. const result = {
  47. info(message?: any, extra?: Record<string, any>) {
  48. write.out(build(message, extra))
  49. },
  50. error(message?: any, extra?: Record<string, any>) {
  51. write.err(build(message, extra))
  52. },
  53. warn(message?: any, extra?: Record<string, any>) {
  54. write.err(build(message, extra))
  55. },
  56. tag(key: string, value: string) {
  57. if (tags) tags[key] = value
  58. return result
  59. },
  60. clone() {
  61. return Log.create({ ...tags })
  62. },
  63. }
  64. return result
  65. }
  66. }