File size: 5,983 Bytes
857cdcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/*
 Chahua Development Thailand
 บริษัทชาหัวประเทศไทย  
 CEO: Saharath C.
 www.chahuadev.com
 chahuadev@gmail.com

/**
 *  Centralized Callback Logger V.11.0.0
 *
 * ระบบจัดการ Log และ Event กลางแบบ Non-Blocking
 *
 *  Features:
 *  Log Levels (info, warn, error, debug)
 *  Console Output with Colors (เพื่อง่ายต่อการอ่าน)
 *  File Logging (บันทึก Log ลงไฟล์ logs/system.log)
 *  Non-Blocking (ไม่รบกวนการทำงานหลักของแอปพลิเคชัน)
 *  Singleton Pattern (ทุกโมดูลใช้ instance เดียวกัน)
 *  Timestamp & Standardized Formatting
 *
 * by Chahuadev Studio V.11.0.0 Enterprise Architecture
 */

const fs = require('fs');
const path = require('path');
const util = require('util');

class CallbackLogger {
    constructor() {
        this.logDirectory = path.join(__dirname, '../logs');
        this.logFilePath = path.join(this.logDirectory, 'system.log');
        this.inMemoryLogs = [];
        this.maxMemoryLogs = 200; // เก็บ Log ในหน่วยความจำสูงสุด 200 รายการ

        this.ensureLogDirectory();
        
        // สร้าง Stream สำหรับเขียนไฟล์แบบ Append (เขียนต่อท้าย)
        this.logStream = fs.createWriteStream(this.logFilePath, { flags: 'a' });

        // สีสำหรับ Console Log
        this.colors = {
            info: '\x1b[36m', // Cyan
            warn: '\x1b[33m', // Yellow
            error: '\x1b[31m', // Red
            debug: '\x1b[35m', // Magenta
            reset: '\x1b[0m'  // Reset color
        };
        
        this.info('logger.init', { message: 'CallbackLogger has started successfully.' });
    }

    /**
     * ตรวจสอบว่าโฟลเดอร์ logs มีอยู่จริงหรือไม่ ถ้าไม่มีให้สร้างใหม่
     */
    ensureLogDirectory() {
        if (!fs.existsSync(this.logDirectory)) {
            try {
                fs.mkdirSync(this.logDirectory, { recursive: true });
                console.log(`[Logger] Created log directory at: ${this.logDirectory}`);
            } catch (error) {
                console.error(`[Logger] Failed to create log directory:`, error);
            }
        }
    }

    /**
     * ฟังก์ชันหลักในการ Log (เป็น private)
     * @param {'info' | 'warn' | 'error' | 'debug'} level ระดับของ Log
     * @param {string} eventName ชื่อของ Event
     * @param {object | string} data ข้อมูลที่ต้องการ Log
     */
    _log(level, eventName, data) {
        const timestamp = new Date().toISOString();
        const icons = { info: '', warn: '', error: '', debug: '' };
        const icon = icons[level] || '';

        // จัดรูปแบบข้อมูลให้สวยงาม
        const formattedData = typeof data === 'object' ? util.inspect(data, { depth: null, colors: false }) : data;
        const formattedDataColor = typeof data === 'object' ? util.inspect(data, { depth: null, colors: true }) : data;

        // สร้างข้อความ Log
        const logMessageForFile = `[${timestamp}] [${level.toUpperCase()}] [${eventName}] ${formattedData}`;
        const logMessageForConsole = `${this.colors[level]}[${timestamp}] ${icon} [${level.toUpperCase()}] [${eventName}]${this.colors.reset} ${formattedDataColor}`;

        // 1. แสดงผลใน Console
        console.log(logMessageForConsole);

        // 2. เขียนลงไฟล์
        this.logStream.write(logMessageForFile + '\n', (err) => {
            if (err) console.error('[Logger] Failed to write to log file:', err);
        });

        // 3. เก็บในหน่วยความจำ (สำหรับเรียกดูย้อนหลัง)
        this.inMemoryLogs.push(logMessageForFile);
        if (this.inMemoryLogs.length > this.maxMemoryLogs) {
            this.inMemoryLogs.shift(); // ลบอันเก่าสุดออก
        }
    }

    /**
     * Log ข้อมูลทั่วไป
     * @param {string} eventName ชื่อ Event (เช่น 'i18n.loaded')
     * @param {object|string} data ข้อมูล
     */
    info(eventName, data) {
        this._log('info', eventName, data);
    }

    /**
     * Log คำเตือน
     * @param {string} eventName ชื่อ Event (เช่น 'license.expiring')
     * @param {object|string} data ข้อมูล
     */
    warn(eventName, data) {
        this._log('warn', eventName, data);
    }

    /**
     * Log ข้อผิดพลาด
     * @param {string} eventName ชื่อ Event (เช่น 'database.connection.failed')
     * @param {object|string} data ข้อมูล
     */
    error(eventName, data) {
        this._log('error', eventName, data);
    }
    
    /**
     * Log ข้อมูลสำหรับการดีบัก
     * @param {string} eventName ชื่อ Event (เช่น 'user.data.raw')
     * @param {object|string} data ข้อมูล
     */
    debug(eventName, data) {
        this._log('debug', eventName, data);
    }

    /**
     * ดึง Log ล่าสุดจากหน่วยความจำ
     * @param {number} limit จำนวนที่ต้องการ
     * @returns {string[]}
     */
    getRecentLogs(limit = 20) {
        return this.inMemoryLogs.slice(-limit);
    }
}

// สร้างและ Export เป็น Singleton Instance เพื่อให้ทุกไฟล์ได้ใช้ตัวเดียวกัน
module.exports = new CallbackLogger();