| 96 | |
| 97 | let last = Date.now() |
| 98 | export function create(tags?: Record<string, any>) { |
| 99 | tags = tags || {} |
| 100 | |
| 101 | const service = tags["service"] |
| 102 | if (service && typeof service === "string") { |
| 103 | const cached = loggers.get(service) |
| 104 | if (cached) { |
| 105 | return cached |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | function build(message: any, extra?: Record<string, any>) { |
| 110 | const prefix = Object.entries({ |
| 111 | ...tags, |
| 112 | ...extra, |
| 113 | }) |
| 114 | .filter(([_, value]) => value !== undefined && value !== null) |
| 115 | .map(([key, value]) => { |
| 116 | const prefix = `${key}=` |
| 117 | if (value instanceof Error) return prefix + formatError(value) |
| 118 | if (typeof value === "object") return prefix + JSON.stringify(value) |
| 119 | return prefix + value |
| 120 | }) |
| 121 | .join(" ") |
| 122 | const next = new Date() |
| 123 | const diff = next.getTime() - last |
| 124 | last = next.getTime() |
| 125 | return [next.toISOString().split(".")[0], "+" + diff + "ms", prefix, message].filter(Boolean).join(" ") + "\n" |
| 126 | } |
| 127 | const result: Logger = { |
| 128 | debug(message?: any, extra?: Record<string, any>) { |
| 129 | if (shouldLog("DEBUG")) { |
| 130 | write("DEBUG " + build(message, extra)) |
| 131 | } |
| 132 | }, |
| 133 | info(message?: any, extra?: Record<string, any>) { |
| 134 | if (shouldLog("INFO")) { |
| 135 | write("INFO " + build(message, extra)) |
| 136 | } |
| 137 | }, |
| 138 | error(message?: any, extra?: Record<string, any>) { |
| 139 | if (shouldLog("ERROR")) { |
| 140 | write("ERROR " + build(message, extra)) |
| 141 | } |
| 142 | }, |
| 143 | warn(message?: any, extra?: Record<string, any>) { |
| 144 | if (shouldLog("WARN")) { |
| 145 | write("WARN " + build(message, extra)) |
| 146 | } |
| 147 | }, |
| 148 | tag(key: string, value: string) { |
| 149 | if (tags) tags[key] = value |
| 150 | return result |
| 151 | }, |
| 152 | clone() { |
| 153 | return Log.create({ ...tags }) |
| 154 | }, |
| 155 | time(message: string, extra?: Record<string, any>) { |