All files / src logger.ts

46.47% Statements 33/71
50% Branches 2/4
33.33% Functions 2/6
46.47% Lines 33/71

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 721x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x     1x 1x                           1x 1x                                   1x  
import type * as vscode from 'vscode';
 
export class Logger {
    private static _outputChannel: vscode.OutputChannel | undefined;
    private static _isVscodeAvailable: boolean | undefined;
 
    private static checkVscode(): boolean {
        if (this._isVscodeAvailable !== undefined) {
            return this._isVscodeAvailable;
        }
        try {
            // We use a dynamic require to avoid failing at top-level if vscode is missing
            // eslint-disable-next-line @typescript-eslint/no-require-imports
            require('vscode');
            this._isVscodeAvailable = true;
        } catch {
            this._isVscodeAvailable = false;
        }
        return this._isVscodeAvailable;
    }
 
    public static init() {
        if (this.checkVscode() && !this._outputChannel) {
            // eslint-disable-next-line @typescript-eslint/no-require-imports
            const vscodeReq = require('vscode');
            this._outputChannel = vscodeReq.window.createOutputChannel('Ollama View');
        }
    }
 
    public static info(message: string) {
        this.log('INFO', message);
    }
 
    public static warn(message: string) {
        this.log('WARN', message);
    }
 
    public static error(message: string, error?: unknown) {
        let fullMessage = message;
        if (error) {
            if (error instanceof Error) {
                fullMessage += `: ${error.message}\n${error.stack}`;
            } else {
                fullMessage += `: ${JSON.stringify(error)}`;
            }
        }
        this.log('ERROR', fullMessage);
        if (this._outputChannel) {
            this._outputChannel.show(true);
        }
    }
 
    private static log(level: string, message: string) {
        const timestamp = new Date().toISOString();
        const formattedMessage = `[${timestamp}] [${level}] ${message}`;

        if (this.checkVscode()) {
            if (!this._outputChannel) {
                this.init();
            }
            this._outputChannel?.appendLine(formattedMessage);
        } else {
            // Fallback to console for tests/CLI
            if (level === 'ERROR') {
                console.error(formattedMessage);
            } else {
                console.log(formattedMessage);
            }
        }
    }
}