File size: 1,856 Bytes
e7ab5f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Structured Logger for OpenClaw
 * Provides consistent JSON logging for HF Spaces
 */

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

// Ensure logs directory exists
const LOG_DIR = path.join(process.env.HOME || '/home/node', 'logs');
if (!fs.existsSync(LOG_DIR)) {
    try {
        fs.mkdirSync(LOG_DIR, { recursive: true });
    } catch (e) {
        // Ignore if we can't create it (might be read-only or race condition)
    }
}

const LOG_FILE = path.join(LOG_DIR, 'app.json.log');

class Logger {
    constructor(moduleName) {
        this.module = moduleName;
    }

    _log(level, message, data = {}) {
        const entry = {
            timestamp: new Date().toISOString(),
            level: level.toUpperCase(),
            module: this.module,
            message,
            ...data
        };

        const jsonLine = JSON.stringify(entry);
        
        // Write to stdout for HF Logs visibility
        console.log(jsonLine);

        // Also append to local file for persistence within container life
        try {
            fs.appendFileSync(LOG_FILE, jsonLine + '\n');
        } catch (e) {
            // Fallback if file write fails
            console.error(`[LOGGER_FAIL] Could not write to log file: ${e.message}`);
        }
    }

    info(message, data) { this._log('INFO', message, data); }
    warn(message, data) { this._log('WARN', message, data); }
    error(message, data) { this._log('ERROR', message, data); }
    debug(message, data) { this._log('DEBUG', message, data); }
    
    // Special method for critical state changes
    state(stateName, previousState, newState, data) {
        this._log('STATE_CHANGE', `State changed: ${stateName}`, {
            previousState,
            newState,
            ...data
        });
    }
}

module.exports = (moduleName) => new Logger(moduleName);