summaryrefslogtreecommitdiffhomepage
path: root/js/src/util/log.ts
blob: 8d316e04ee191293340ecbd4fbb84160a199b979 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import fs from "node:fs";
import path from "node:path";
import { AppPath } from "../app/path";
export namespace Log {
  const write = {
    out: (msg: string) => {
      process.stdout.write(msg);
    },
    err: (msg: string) => {
      process.stderr.write(msg);
    },
  };

  export function file(directory: string) {
    const out = Bun.file(
      path.join(AppPath.data(directory), "opencode.out.log"),
    );
    const err = Bun.file(
      path.join(AppPath.data(directory), "opencode.err.log"),
    );
    write["out"] = (msg) => out.write(msg);
    write["err"] = (msg) => err.write(msg);
  }

  export function create(tags?: Record<string, any>) {
    tags = tags || {};

    function build(message: any, extra?: Record<string, any>) {
      const prefix = Object.entries({
        ...tags,
        ...extra,
      })
        .map(([key, value]) => `${key}=${value}`)
        .join(" ");
      return [prefix, message].join(" ") + "\n";
    }
    const result = {
      info(message?: any, extra?: Record<string, any>) {
        write.out(build(message, extra));
      },
      error(message?: any, extra?: Record<string, any>) {
        write.err(build(message, extra));
      },
      tag(key: string, value: string) {
        if (tags) tags[key] = value;
        return result;
      },
      clone() {
        return Log.create({ ...tags });
      },
    };

    return result;
  }
}