| 1 | import winston from "winston"; |
| 2 | import { captureException } from "./sentry/SentryLogger"; |
| 3 | |
| 4 | class LoggerClass { |
| 5 | private static instance: LoggerClass; |
| 6 | private winston: winston.Logger; |
| 7 | |
| 8 | private constructor() { |
| 9 | this.winston = winston.createLogger({ |
| 10 | level: "info", |
| 11 | format: winston.format.combine( |
| 12 | winston.format.colorize(), |
| 13 | winston.format.timestamp(), |
| 14 | winston.format.printf(({ level, message, timestamp, ...meta }) => { |
| 15 | const metaStr = Object.keys(meta).length |
| 16 | ? ` ${JSON.stringify(meta)}` |
| 17 | : ""; |
| 18 | return `[@continuedev] ${level}: ${message}${metaStr}`; |
| 19 | }), |
| 20 | ), |
| 21 | transports: [ |
| 22 | // Write all logs with importance level of `info` or higher to `info.log` |
| 23 | ...(process.env.NODE_ENV === "test" |
| 24 | ? [ |
| 25 | new winston.transports.File({ |
| 26 | filename: "e2e.log", |
| 27 | level: "info", |
| 28 | }), |
| 29 | ] |
| 30 | : []), |
| 31 | // Normal console.log behavior |
| 32 | new winston.transports.Console(), |
| 33 | ], |
| 34 | }); |
| 35 | } |
| 36 | |
| 37 | public static getInstance(): LoggerClass { |
| 38 | if (!LoggerClass.instance) { |
| 39 | LoggerClass.instance = new LoggerClass(); |
| 40 | } |
| 41 | return LoggerClass.instance; |
| 42 | } |
| 43 | |
| 44 | private shouldSendToSentry(): boolean { |
| 45 | return process.env.NODE_ENV !== "test" && process.env.NODE_ENV !== "e2e"; |
| 46 | } |
| 47 | |
| 48 | public log(message: string, meta?: any): void { |
| 49 | this.winston.info(message, meta); |
| 50 | } |
| 51 | |
| 52 | public debug(message: string, meta?: any): void { |
| 53 | this.winston.debug(message, meta); |
| 54 | } |
| 55 | |
| 56 | public info(message: string, meta?: any): void { |
| 57 | this.winston.info(message, meta); |
| 58 | } |
| 59 | |
| 60 | public warn(message: string, meta?: any): void { |
| 61 | this.winston.warn(message, meta); |
| 62 | } |
| 63 | |
| 64 | public error( |
| 65 | error: Error | string | unknown, |
| 66 | context?: Record<string, any>, |
| 67 | ): void { |
| 68 | let errorMessage: string; |
| 69 | |
| 70 | if (error instanceof Error) { |
| 71 | errorMessage = error.message; |
| 72 | } else if (typeof error === "string") { |
| 73 | errorMessage = error; |
| 74 | } else { |
| 75 | errorMessage = "An unknown error occurred"; |
| 76 | } |
| 77 | |
| 78 | this.winston.error(errorMessage, context); |
| 79 | |
| 80 | if (this.shouldSendToSentry() && error instanceof Error) { |
| 81 | captureException(error, context); |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | export const Logger = LoggerClass.getInstance(); |