log.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { Context } from "../context"
  2. export namespace Log {
  3. const ctx = Context.create<{
  4. tags: Record<string, any>
  5. }>()
  6. export function create(tags?: Record<string, any>) {
  7. tags = tags || {}
  8. const result = {
  9. info(message?: any, extra?: Record<string, any>) {
  10. const prefix = Object.entries({
  11. ...use().tags,
  12. ...tags,
  13. ...extra,
  14. })
  15. .map(([key, value]) => `${key}=${value}`)
  16. .join(" ")
  17. console.log(prefix, message)
  18. return result
  19. },
  20. tag(key: string, value: string) {
  21. if (tags) tags[key] = value
  22. return result
  23. },
  24. clone() {
  25. return Log.create({ ...tags })
  26. },
  27. }
  28. return result
  29. }
  30. export function provide<R>(tags: Record<string, any>, cb: () => R) {
  31. const existing = use()
  32. return ctx.provide(
  33. {
  34. tags: {
  35. ...existing.tags,
  36. ...tags,
  37. },
  38. },
  39. cb,
  40. )
  41. }
  42. function use() {
  43. try {
  44. return ctx.use()
  45. } catch (e) {
  46. return { tags: {} }
  47. }
  48. }
  49. }