All files / logger Writer.ts

88.88% Statements 16/18
50% Branches 1/2
100% Functions 3/3
88.88% Lines 16/18

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 532x 2x           2x               2x 2x     2x                   6x 6x 6x 6x 6x                 6x 6x 6x   6x 6x          
import * as fs from 'fs';
import * as path from 'path';
 
/**
 * @class Writer
 * @description Handles writing log messages to files.
 */
export class Writer {
    private logDirectory: string;
 
    /**
     * @constructor
     * @description Initializes the Writer by ensuring the log directory exists.
     */
    constructor() {
        const logsDir = path.join(process.cwd(), 'logs');
        Iif (!fs.existsSync(logsDir)) {
            fs.mkdirSync(logsDir, { recursive: true });
        }
        this.logDirectory = logsDir;
    }
 
    /**
     * @method getLogFilePath
     * @private
     * @description Generates the path for the current day's log file.
     * @returns {string} The absolute path to the log file.
     */
    private getLogFilePath(): string {
        const date = new Date();
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return path.join(this.logDirectory, `${year}-${month}-${day}.log`);
    }
 
    /**
     * @method write
     * @description Writes a message to the daily log file.
     * @param {string} message - The log message to write.
     */
    public write(message: string): void {
        const logFilePath = this.getLogFilePath();
        const timestamp = new Date().toISOString();
        const logMessage = `${timestamp} - ${message}\n`;
 
        try {
            fs.appendFileSync(logFilePath, logMessage);
        } catch (err) {
            console.error('Failed to write to log file:', err);
        }
    }
}