summaryrefslogtreecommitdiffhomepage
path: root/packages/console/core/src/util/log.ts
blob: ef3ad85c6b60423de61d3196bc17392b60292fe7 (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 { Context } from "../context"

export namespace Log {
  const ctx = Context.create<{
    tags: Record<string, any>
  }>()

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

    const result = {
      info(message?: any, extra?: Record<string, any>) {
        const prefix = Object.entries({
          ...use().tags,
          ...tags,
          ...extra,
        })
          .map(([key, value]) => `${key}=${value}`)
          .join(" ")
        console.log(prefix, message)
        return result
      },
      tag(key: string, value: string) {
        if (tags) tags[key] = value
        return result
      },
      clone() {
        return Log.create({ ...tags })
      },
    }

    return result
  }

  export function provide<R>(tags: Record<string, any>, cb: () => R) {
    const existing = use()
    return ctx.provide(
      {
        tags: {
          ...existing.tags,
          ...tags,
        },
      },
      cb,
    )
  }

  function use() {
    try {
      return ctx.use()
    } catch {
      return { tags: {} }
    }
  }
}