All files / modules historyLogger.ts

91.66% Statements 22/24
100% Branches 2/2
75% Functions 3/4
91.66% Lines 22/24

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 481x 1x 1x     1x   1x 1x   1x       4x     4x     4x 4x       2x 2x 2x 2x 2x 2x 2x       2x 2x   2x 2x                
import * as fs from 'fs/promises';
import * as path from 'path';
import dotenv from 'dotenv';
 
// Load environment variables to get the context directory path
dotenv.config();
 
const DEFAULT_CONTEXT_DIR = './lamplighter_context';
const LOG_FILE_NAME = 'history_log.md';
 
export class HistoryLogger {
    private logFilePath: string;
 
    constructor() {
        const contextDir = process.env.LAMPLIGHTER_CONTEXT_DIR || DEFAULT_CONTEXT_DIR;
        // Ensure the context directory exists, create if not
        // Note: fs.mkdir with recursive: true is idempotent (doesn't throw if dir exists)
        fs.mkdir(contextDir, { recursive: true })
          .catch(err => console.error(`[HistoryLogger] Error creating context directory ${contextDir}:`, err));
        
        this.logFilePath = path.join(contextDir, LOG_FILE_NAME);
        console.log(`[HistoryLogger] Initialized. Logging to: ${this.logFilePath}`);
    }
 
    private formatTimestamp(date: Date): string {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');
        return `[${year}-${month}-${day} ${hours}:${minutes}:${seconds}]`;
    }
 
    async log(message: string): Promise<void> {
        const timestamp = this.formatTimestamp(new Date());
        const logEntry = `${timestamp} - ${message}\n`;
 
        try {
            await fs.appendFile(this.logFilePath, logEntry, 'utf-8');
        } catch (error) {
            console.error(`[HistoryLogger] Failed to append to log file ${this.logFilePath}:`, error);
            // Decide if we should throw, retry, or just log the error
            // For now, just logging the error.
        }
    }
}