All files / src logger.ts

71.36% Statements 172/241
69.81% Branches 37/53
86.95% Functions 20/23
71.36% Lines 172/241

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 3311x 1x             1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   63x 63x 63x 63x 63x   63x 63x 63x 63x 63x 63x 63x 63x 63x 63x                     63x 63x     63x 63x 63x   63x 63x 63x 63x 63x   63x                                                   1x 96x 96x 96x 96x   96x 88x 88x 88x 88x 88x 88x 88x 88x   96x                                 96x 79x 79x   96x 212x 212x     212x 212x     96x 11x 11x   96x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x   63x   63x   63x 63x   96x 14x 14x   96x 9x 9x 9x 9x 9x 9x 9x 9x   9x   9x 9x     9x 9x 9x 9x 9x 9x 9x 9x   9x 9x 9x 9x 9x 9x 9x 9x   96x 7x 7x   96x 33x 33x   96x               96x 97x 80x 80x 97x 97x   96x 51x 51x 51x 51x 40x 40x 11x 11x 11x 11x 11x 11x 11x 15x     51x   96x 157x 157x   157x   96x 9x 2x 2x   9x 4x 4x   3x 3x 3x 3x 3x 3x 9x     9x 96x         7x 7x 7x   7x 7x 7x   6x 6x 6x                                                                                                
import * as vscode from "vscode";
import {
    BrowserClient,
    defaultStackParser,
    getDefaultIntegrations,
    makeFetchTransport,
    Scope,
} from "@sentry/browser";
import { IMcpLogger, isApiError, isAuthError } from "@dataflint/mcp-server";
import { TelemetryEventName, TelemetryEventProps } from "./telemetry-events";
 
// ANSI color codes for Debug Console (only used when coloredOutput is enabled)
const COLORS = {
    reset: "\x1b[0m",
    bright: "\x1b[1m",
    dim: "\x1b[2m",
    cyan: "\x1b[36m",
    green: "\x1b[32m",
    yellow: "\x1b[33m",
    red: "\x1b[31m",
    magenta: "\x1b[35m",
};
 
const PREFIX_PLAIN = "[DataFlint]";
const PREFIX_COLORED = `${COLORS.bright}${COLORS.magenta}[🔥 DataFlint]${COLORS.reset}`;
 
function isColoredOutputEnabled(): boolean {
    return vscode.workspace
        .getConfiguration("dataflint-copilot.logging")
        .get<boolean>("coloredOutput", false);
}
 
function getTimestamp(): string {
    const now = new Date();
    const time = now.toLocaleTimeString("en-US", {
        hour12: false,
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
    });
    return `${time}.${now.getMilliseconds().toString().padStart(3, "0")}`;
}
 
export interface LogContext {
    operation?: string;
    component?: string;
    jobId?: number;
    applicationId?: number;
    filePath?: string;
    [key: string]: unknown;
}
 
function formatContext(context?: LogContext): string {
    if (!context || Object.keys(context).length === 0) return "";
 
    const prefix = context.operation || context.component;
    const rest = { ...context };
    delete rest.operation;
    delete rest.component;
 
    let result = prefix ? `[${prefix}] ` : "";
    const pairs = Object.entries(rest)
        .filter(([, v]) => v !== undefined && v !== null)
        .map(([k, v]) => `${k}=${JSON.stringify(v)}`)
        .join(" ");
 
    if (pairs) result += `{${pairs}} `;
    return result;
}
 
/** The Sentry surface Logger consumes — a real Scope satisfies it; tests inject a fake. */
export interface SentryScopeLike {
    setUser(user: { id: string }): void;
    setTag(key: string, value: string): void;
    setContext(name: string, context: Record<string, unknown>): void;
    addBreadcrumb(breadcrumb: {
        category: string;
        message: string;
        level: "info";
        data?: Record<string, unknown>;
    }): void;
    captureException(err: Error): void;
}
 
export interface LoggerDeps {
    outputChannel: vscode.OutputChannel;
    /** Live getter — the environment setting can change mid-session. */
    getEnvironment: () => string;
    /** Absent → Sentry reporting disabled (development mode). */
    scope?: SentryScopeLike;
}
 
export class Logger implements IMcpLogger {
    private static instance: Logger | undefined;
    private readonly outputChannel: vscode.OutputChannel;
    private readonly getEnvironment: () => string;
    private readonly scope?: SentryScopeLike;
 
    constructor(deps: LoggerDeps) {
        this.outputChannel = deps.outputChannel;
        this.getEnvironment = deps.getEnvironment;
        this.scope = deps.scope;
        this.identify(undefined);
        this.trackEvent("session_start", {
            environment: this.getEnvironment(),
        });
    }
 
    static init(
        context: vscode.ExtensionContext,
        outputChannel: vscode.OutputChannel,
        getEnvironment: () => string
    ): Logger {
        if (!Logger.instance) {
            Logger.setInstance(
                new Logger({
                    outputChannel,
                    getEnvironment,
                    scope: createSentryScope(context),
                })
            );
        }
        return Logger.instance as Logger;
    }
 
    static setInstance(logger: Logger): void {
        Logger.instance = logger;
    }
 
    static getInstance(): Logger {
        if (!Logger.instance)
            throw new Error(
                "Logger not initialized. Call Logger.init() first."
            );
        return Logger.instance;
    }
 
    /** Get logger if available, for optional logging where init order is uncertain. */
    static tryGetInstance(): Logger | undefined {
        return Logger.instance;
    }
 
    private logCore(
        level: "INFO" | "WARN" | "DEBUG" | "ERROR",
        message: string,
        context?: LogContext,
        consoleMethod: "log" | "warn" | "error" = "log",
        color: string = COLORS.reset,
        extraArgs: unknown[] = []
    ): void {
        const contextStr = formatContext(context);
        this.outputChannel.appendLine(
            `[${new Date().toISOString()}] ${level}: ${contextStr}${message}`
        );
 
        const consoleMsg = isColoredOutputEnabled()
            ? `${COLORS.dim}${getTimestamp()}${COLORS.reset} ${PREFIX_COLORED} ${color}${level}${COLORS.reset} ${color}${contextStr}${message}${COLORS.reset}`
            : `${getTimestamp()} ${PREFIX_PLAIN} ${level} ${contextStr}${message}`;
 
        console[consoleMethod](consoleMsg, ...extraArgs);
    }
 
    info(message: string, context?: LogContext): void {
        this.logCore("INFO", message, context, "log", COLORS.green);
    }
 
    error(
        message: string,
        error?: unknown,
        contextOrString?: LogContext | string
    ): void {
        const legacyContext =
            typeof contextOrString === "string" ? contextOrString : undefined;
        const context =
            typeof contextOrString === "string"
                ? { operation: contextOrString }
                : contextOrString;
 
        const errorDetail = error
            ? ` - ${error instanceof Error ? error.message : String(error)}${error instanceof Error && error.stack ? ` Stack: ${error.stack}` : ""}`
            : "";
 
        this.logCore(
            "ERROR",
            `${message}${errorDetail}`,
            context,
            "error",
            COLORS.red,
            error ? [error] : []
        );
 
        if (error instanceof Error) {
            this.captureError(error, {
                context: legacyContext || context?.operation || "unknown",
                logMessage: message,
                ...context,
            });
        }
    }
 
    warn(message: string, context?: LogContext): void {
        this.logCore("WARN", message, context, "warn", COLORS.yellow);
    }
 
    debug(message: string, context?: LogContext): void {
        this.logCore("DEBUG", message, context, "log", COLORS.dim);
    }
 
    show(): void {
        this.outputChannel.show();
    }
 
    /**
     * Identify the user for distinct-count only — opaque JWT `sub` when
     * authenticated, anonymous machineId otherwise. Never names or emails.
     */
    identify(subId: string | undefined): void {
        if (!this.sentryEnabled() || !this.scope) {
            return;
        }
        this.scope.setUser({ id: subId ?? vscode.env.machineId });
    }
 
    trackEvent<N extends TelemetryEventName>(
        name: N,
        props: TelemetryEventProps<N>
    ): void {
        if (!this.sentryEnabled() || !this.scope) {
            return;
        }
        try {
            this.scope.addBreadcrumb({
                category: "telemetry",
                message: name,
                level: "info",
                data: props,
            });
        } catch (error) {
            console.error("Failed to track event:", error);
        }
    }
 
    private sentryEnabled(): boolean {
        return (
            this.scope !== undefined && vscode.env.isTelemetryEnabled !== false
        );
    }
 
    private captureError(err: Error, context: Record<string, unknown>): void {
        if (!this.sentryEnabled() || !this.scope) {
            return;
        }
 
        if (isUserResolvableCondition(err)) {
            return;
        }
 
        try {
            this.scope.setContext("error_context", {
                environment: this.getEnvironment(),
                ...context,
            });
            this.scope.captureException(err);
        } catch (error) {
            console.error("Failed to capture exception:", error);
        }
    }
}
 
// Sentry issues are faults we should fix; a condition the user resolves inline
// is not one. Everything not matched here reports: 5xx, network outages, and
// untyped exceptions.
function isUserResolvableCondition(err: Error): boolean {
    return isRejectedRequest(err) || isSignInRequired(err);
}
 
function isRejectedRequest(err: Error): boolean {
    return isApiError(err) && err.statusCode < 500;
}
 
function isSignInRequired(err: Error): boolean {
    return isAuthError(err);
}
 
function createSentryScope(
    context: vscode.ExtensionContext
): SentryScopeLike | undefined {
    if (context.extensionMode !== vscode.ExtensionMode.Production) {
        console.log("Telemetry disabled in development mode");
        return undefined;
    }
 
    try {
        const integrations = getDefaultIntegrations({}).filter(
            (integration) =>
                !["BrowserApiErrors", "Breadcrumbs", "GlobalHandlers"].includes(
                    integration.name
                )
        );
 
        const extensionVersion = context.extension?.packageJSON?.version;
 
        const client = new BrowserClient({
            dsn: "https://1c9233c712c55dca22dde944bbc472cb@o4510413238173696.ingest.us.sentry.io/4510413301874698",
            transport: makeFetchTransport,
            stackParser: defaultStackParser,
            integrations: integrations,
            release: extensionVersion,
        });
 
        const scope = new Scope();
        scope.setClient(client);
        client.init();
 
        scope.setTag("vscode.version", vscode.version);
        scope.setTag(
            "extension.mode",
            vscode.ExtensionMode[context.extensionMode]
        );
        if (extensionVersion) {
            scope.setTag("extension.version", extensionVersion);
        }
 
        console.log("Telemetry initialized successfully");
        return scope;
    } catch (error) {
        console.error("Failed to initialize telemetry:", error);
        return undefined;
    }
}