| 1 | import crypto from "crypto"; |
| 2 | import fs from "fs"; |
| 3 | import path from "path"; |
| 4 | |
| 5 | import chalk from "chalk"; |
| 6 | import winston from "winston"; |
| 7 | |
| 8 | import { env } from "../env.js"; |
| 9 | import { sentryService } from "../sentry.js"; |
| 10 | |
| 11 | const { combine, timestamp, printf, errors } = winston.format; |
| 12 | |
| 13 | // Generate a unique session ID for this process |
| 14 | const SESSION_ID = crypto.randomBytes(4).toString("hex"); |
| 15 | |
| 16 | // Get log directory |
| 17 | function getLogDir(): string { |
| 18 | const logDir = path.join(env.continueHome, "logs"); |
| 19 | |
| 20 | // Create directory if it doesn't exist |
| 21 | if (!fs.existsSync(logDir)) { |
| 22 | fs.mkdirSync(logDir, { recursive: true }); |
| 23 | } |
| 24 | |
| 25 | return logDir; |
| 26 | } |
| 27 | |
| 28 | // Get current log file path |
| 29 | function getLogFilePath(): string { |
| 30 | const logDir = getLogDir(); |
| 31 | return path.join(logDir, "cn.log"); |
| 32 | } |
| 33 | |
| 34 | // Simple replacer for JSON.stringify to handle common issues |
| 35 | function createReplacer() { |
| 36 | const seen = new Set(); |
| 37 | |
| 38 | return (key: string, value: any) => { |
| 39 | // Handle circular references |
| 40 | if (typeof value === "object" && value !== null) { |
| 41 | if (seen.has(value)) { |
| 42 | return "[Circular]"; |
| 43 | } |
| 44 | seen.add(value); |
| 45 | } |
| 46 | |
| 47 | // Handle functions |
| 48 | if (typeof value === "function") { |
| 49 | return "[Function]"; |
| 50 | } |
| 51 | |
| 52 | // Handle undefined (which JSON.stringify skips by default) |
| 53 | if (value === undefined) { |
| 54 | return "[undefined]"; |
| 55 | } |
| 56 | |
| 57 | return value; |
| 58 | }; |
| 59 | } |
| 60 | |
| 61 | // Custom format for log output |
| 62 | const logFormat = printf( |
| 63 | ({ level, message, timestamp, stack, ...metadata }) => { |
| 64 | let msg = `${timestamp} [${SESSION_ID}] [${level}]: ${message}`; |
| 65 | |
| 66 | // Add metadata if present |
| 67 | if (Object.keys(metadata).length > 0) { |
| 68 | try { |
| 69 | msg += ` ${JSON.stringify(metadata, createReplacer())}`; |
| 70 | } catch (err) { |
| 71 | // Fallback if stringify still fails somehow |
| 72 | msg += ` [Failed to stringify metadata: ${err}]`; |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | // Add stack trace for errors |
| 77 | if (stack) { |
| 78 | msg += `\n${stack}`; |
| 79 | } |
| 80 | |
| 81 | return msg; |
| 82 | }, |
| 83 | ); |
| 84 | |
| 85 | // Track headless mode |
| 86 | let isHeadlessMode = false; |
| 87 | |
| 88 | // Create the winstonLogger instance |
| 89 | const winstonLogger = winston.createLogger({ |
| 90 | level: "info", // Default level |
| 91 | format: combine( |
| 92 | errors({ stack: true }), |
| 93 | timestamp({ format: "YYYY-MM-DD HH:mm:ss.SSS" }), |
| 94 | logFormat, |
| 95 | ), |
| 96 | transports: [ |
| 97 | // File transport for all logs |
| 98 | new winston.transports.File({ |
| 99 | filename: getLogFilePath(), |
| 100 | maxsize: 10 * 1024 * 1024, // 10MB |
| 101 | maxFiles: 5, |
| 102 | }), |
| 103 | ], |
| 104 | }); |
| 105 | |
| 106 | // Function to set log level |
| 107 | export function setLogLevel(level: string) { |
| 108 | winstonLogger.level = level; |
| 109 | } |
| 110 | |
| 111 | // Function to configure headless mode |
| 112 | export function configureHeadlessMode(headless: boolean) { |
| 113 | isHeadlessMode = headless; |
| 114 | } |
| 115 | |
| 116 | // Export winstonLogger methods |
| 117 | export const logger = { |
| 118 | debug: (message: string, meta?: any) => winstonLogger.debug(message, meta), |
| 119 | info: (message: string, meta?: any) => winstonLogger.info(message, meta), |
| 120 | warn: (message: string, meta?: any) => { |
| 121 | winstonLogger.warn(message, meta); |
| 122 | sentryService.captureMessage(message, "warning", meta); |
| 123 | }, |
| 124 | error: (message: string, error?: Error | any, meta?: any) => { |
| 125 | if (error instanceof Error) { |
| 126 | winstonLogger.error(message, { |
| 127 | ...meta, |
| 128 | error: error.message, |
| 129 | stack: error.stack, |
| 130 | }); |
| 131 | sentryService.captureException(error, { message, ...meta }); |
| 132 | } else if (error) { |
| 133 | winstonLogger.error(message, { ...meta, error }); |
| 134 | sentryService.captureMessage( |
| 135 | `${message}: ${String(error)}`, |
| 136 | "error", |
| 137 | meta, |
| 138 | ); |
| 139 | } else { |
| 140 | winstonLogger.error(message, meta); |
| 141 | sentryService.captureMessage(message, "error", meta); |
| 142 | } |
| 143 | |
| 144 | // In headless mode, also output to stderr |
| 145 | if (isHeadlessMode) { |
| 146 | if (error instanceof Error) { |
| 147 | console.error(chalk.red(`${message}: ${error.message}`)); |
| 148 | } else if (error) { |
| 149 | console.error(chalk.red(`${message}: ${error}`)); |
| 150 | } else { |
| 151 | console.error(chalk.red(message)); |
| 152 | } |
| 153 | } |
| 154 | }, |
| 155 | setLevel: setLogLevel, |
| 156 | configureHeadlessMode, |
| 157 | getLogPath: getLogFilePath, |
| 158 | getSessionId: () => SESSION_ID, |
| 159 | }; |