1 import { track } from "@medusajs/telemetry"
2 import ora from "ora"
3 import stackTrace from "stack-trace"
4 import { ulid } from "ulid"
5 import { inspect } from "util"
6 import winston from "winston"
7 import { panicHandler } from "./panic-handler"
8
9 const LOG_LEVEL = process.env.LOG_LEVEL || "http"
10 const LOG_FILE = process.env.LOG_FILE || ""
11 const NODE_ENV = process.env.NODE_ENV || "development"
12 const IS_DEV = NODE_ENV.startsWith("dev")
13
14 let transports: winston.transport[] = []
15
16 if (!IS_DEV) {
17 transports.push(new winston.transports.Console())
18 } else {
19 transports.push(
20 new winston.transports.Console({
21 format: winston.format.combine(
22 winston.format.cli({
23 levels: winston.config.npm.levels,
24 }),
25 winston.format.splat()
26 ),
27 })
28 )
29 }
30
31 if (LOG_FILE) {
32 transports.push(
33 new winston.transports.File({
34 filename: LOG_FILE,
35 })
36 )
37 }
38
39 const loggerInstance = winston.createLogger({
40 level: LOG_LEVEL,
41 levels: winston.config.npm.levels,
42 format: winston.format.combine(
43 winston.format.timestamp({
44 format: "YYYY-MM-DD HH:mm:ss",
45 }),
46 winston.format.errors({ stack: true }),
47 winston.format.splat(),
48 winston.format.json()
49 ),
50 transports,
51 })
52
53 export class Reporter {
54 protected activities_: Record<string, any>
55 protected loggerInstance_: winston.Logger
56 protected ora_: typeof ora
57
58 constructor({ logger, activityLogger }) {
59 this.activities_ = {}
60 this.loggerInstance_ = logger
61 this.ora_ = activityLogger
62 }
63
64 panic(data) {
65 const parsedPanic = panicHandler(data)
66
67 this.loggerInstance_.log({
68 level: "error",
69 details: data,
70 message: parsedPanic.message,
71 })
72
73 track("PANIC_ERROR_REACHED", {
74 id: data.id,
75 })
76
77 process.exit(1)
78 }
79
80 /**
81 * Determines if the logger should log at a given level.
82 * @param {string} level - the level to check if logger is configured for
83 * @return {boolean} whether we should log
84 */
85 shouldLog = (level: string) => {
86 const levelValue = this.loggerInstance_.levels[level]
87 const logLevel = this.loggerInstance_.levels[this.loggerInstance_.level]
88 return levelValue <= logLevel
89 }
90
91 /**
92 * Sets the log level of the logger.
93 * @param {string} level - the level to set the logger to
94 */
95 setLogLevel(level: string) {
96 this.loggerInstance_.level = level
97 }
98
99 /**
100 * Resets the logger to the value specified by the LOG_LEVEL env var. If no
101 * LOG_LEVEL is set it defaults to "silly".
102 */
103 unsetLogLevel() {
104 this.loggerInstance_.level = LOG_LEVEL
105 }
106
107 /**
108 * Begin an activity. In development an activity is displayed as a spinner;
109 * in other environments it will log the activity at the info level.
110 * @param {string} message - the message to log the activity under
111 * @param {any} config
112 * @returns {string} the id of the activity; this should be passed to do
113 * further operations on the activity such as success, failure, progress.
114 */
115 activity(message: string, config: any = {}) {
116 const id = ulid()
117 if (IS_DEV && this.shouldLog("info")) {
118 const activity = this.ora_(message).start()
119
120 this.activities_[id] = {
121 activity,
122 config,
123 start: Date.now(),
124 }
125
126 return id
127 } else {
128 this.activities_[id] = {
129 start: Date.now(),
130 config,
131 }
132 this.loggerInstance_.log({
133 activity_id: id,
134 level: "info",
135 config,
136 message,
137 })
138
139 return id
140 }
141 }
142
143 /**
144 * Reports progress on an activity. In development this will update the
145 * activity log message, in other environments a log message will be issued
146 * at the info level. Logging will include the activityId.
147 * @param {string} activityId - the id of the activity as returned by activity
148 * @param {string} message - the message to log
149 */
150 progress(activityId: string, message: string) {
151 const toLog = {
152 level: "info",
153 message,
154 }
155
156 if (this.activities_[activityId]) {
157 const activity = this.activities_[activityId]
158 if (activity.activity) {
159 activity.text = message
160 } else {
161 toLog["activity_id"] = activityId
162 this.loggerInstance_.log(toLog)
163 }
164 } else {
165 this.loggerInstance_.log(toLog)
166 }
167 }
168
169 /**
170 * Logs an error. If an error object is provided the stack trace for the error
171 * will also be logged.
172 * @param {String | Error} messageOrError - can either be a string with a
173 * message to log the error under; or an error object.
174 * @param {Error?} error - an error object to log message with
175 * Level 0
176 */
177 error(messageOrError: string | Error, error?: Error) {
178 let message: string
179 let errorAsObject: Error | undefined
180
181 if (messageOrError && typeof messageOrError === "object") {
182 message = ""
183 errorAsObject = messageOrError
184 } else {
185 message = messageOrError
186 errorAsObject = error
187 }
188
189 const toLog = {
190 level: "error",
191 message,
192 }
193
194 if (errorAsObject) {
195 toLog["message"] = toLog.message
196 ? `${toLog.message}: ${errorAsObject.message}`
197 : errorAsObject.message
198 toLog["stack"] = stackTrace.parse(errorAsObject)
199 /**
200 * Winston only logs the error properties when they are
201 * string values. Hence we will have to self convert
202 * the error cause to a string
203 */
204 const cause = (errorAsObject as any)?.cause
205 if (cause) {
206 toLog["cause"] = inspect(cause)
207 }
208 }
209
210 this.loggerInstance_.log(toLog)
211
212 /**
213 * In dev we print the error using `console.error`, because Winston
214 * CLI formatter does not print the error stack in that case
215 */
216 if (errorAsObject && IS_DEV) {
217 console.error(errorAsObject)
218 }
219 }
220
221 /**
222 * Reports failure of an activity. In development the activity will be udpated
223 * with the failure message in other environments the failure will be logged
224 * at the error level.
225 * @param {string} activityId - the id of the activity as returned by activity
226 * @param {string} message - the message to log
227 * @returns {object} data about the activity
228 */
229 failure(activityId: string, message: string) {
230 const time = Date.now()
231 const toLog = {
232 level: "error",
233 message,
234 }
235
236 if (this.activities_[activityId]) {
237 const activity = this.activities_[activityId]
238 if (activity.activity) {
239 activity.activity.fail(`${message} – ${time - activity.start}`)
240 } else {
241 toLog["duration"] = time - activity.start
242 toLog["activity_id"] = activityId
243 this.loggerInstance_.log(toLog)
244 }
245 } else {
246 this.loggerInstance_.log(toLog)
247 }
248
249 if (this.activities_[activityId]) {
250 const activity = this.activities_[activityId]
251 return {
252 ...activity,
253 duration: time - activity.start,
254 }
255 }
256
257 return null
258 }
259
260 /**
261 * Reports success of an activity. In development the activity will be udpated
262 * with the failure message in other environments the failure will be logged
263 * at the info level.
264 * @param {string} activityId - the id of the activity as returned by activity
265 * @param {string} message - the message to log
266 * @returns {Record<string, any>} data about the activity
267 */
268 success(activityId: string, message: string) {
269 const time = Date.now()
270 const toLog = {
271 level: "info",
272 message,
273 }
274
275 if (this.activities_[activityId]) {
276 const activity = this.activities_[activityId]
277 if (activity.activity) {
278 activity.activity.succeed(`${message} – ${time - activity.start}ms`)
279 } else {
280 toLog["duration"] = time - activity.start
281 toLog["activity_id"] = activityId
282 this.loggerInstance_.log(toLog)
283 }
284 } else {
285 this.loggerInstance_.log(toLog)
286 }
287
288 if (this.activities_[activityId]) {
289 const activity = this.activities_[activityId]
290 return {
291 ...activity,
292 duration: time - activity.start,
293 }
294 }
295
296 return null
297 }
298
299 /**
300 * Logs a message at the silly level.
301 * @param {string} message - the message to log
302 * Level 6
303 */
304 silly(message: string) {
305 this.loggerInstance_.log({
306 level: "silly",
307 message,
308 })
309 }
310
311 /**
312 * Logs a message at the info level.
313 * @param {string} message - the message to log
314 * Level 5
315 */
316 debug(message: string) {
317 this.loggerInstance_.log({
318 level: "debug",
319 message,
320 })
321 }
322
323 /**
324 * Logs a message at the verbose level.
325 * @param {string} message - the message to log
326 * Level 4
327 */
328 verbose(message: string) {
329 this.loggerInstance_.log({
330 level: "verbose",
331 message,
332 })
333 }
334
335 /**
336 * Logs a message at the http level.
337 * @param {string} message - the message to log
338 * Level 3
339 */
340 http(message: string) {
341 this.loggerInstance_.log({
342 level: "http",
343 message,
344 })
345 }
346
347 /**
348 * Logs a message at the info level.
349 * @param {string} message - the message to log
350 * Level 2
351 */
352 info(message: string) {
353 this.loggerInstance_.log({
354 level: "info",
355 message,
356 })
357 }
358
359 /**
360 * Logs a message at the warn level.
361 * @param {string} message - the message to log
362 * Level 1
363 */
364 warn(message: string) {
365 this.loggerInstance_.warn({
366 level: "warn",
367 message,
368 })
369 }
370
371 /**
372 * A wrapper around winston's log method.
373 */
374 log(...args) {
375 if (args.length > 1) {
376 // @ts-ignore
377 this.loggerInstance_.log(...args)
378 } else {
379 let message = args[0]
380 this.loggerInstance_.log({
381 level: "info",
382 message,
383 })
384 }
385 }
386 }
387
388 const logger = new Reporter({
389 logger: loggerInstance,
390 activityLogger: ora,
391 })
392
393 export default logger