summaryrefslogtreecommitdiff
path: root/src/debug/Log.cpp
blob: a864f0d27e917457413305d67a6c5f9d09fc8179 (plain)
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
#include "Log.hpp"
#include "../defines.hpp"
#include "../Compositor.hpp"

#include <fstream>
#include <iostream>

void Debug::init(std::string IS) {
    if (ISDEBUG)
        logFile = "/tmp/hypr/" + IS + "/hyprlandd.log";
    else
        logFile = "/tmp/hypr/" + IS + "/hyprland.log";
}

void Debug::log(LogLevel level, const char* fmt, ...) {

    // log to a file
    std::ofstream ofs;
    ofs.open(logFile, std::ios::out | std::ios::app);

    switch (level) {
        case LOG:
            ofs << "[LOG] ";
            break;
        case WARN:
            ofs << "[WARN] ";
            break;
        case ERR:
            ofs << "[ERR] ";
            break;
        case CRIT:
            ofs << "[CRITICAL] ";
            break;
        case INFO:
            ofs << "[INFO] ";
            break;
        default:
            break;
    }

    char buf[LOGMESSAGESIZE] = "";
    char* outputStr;
    int logLen;

    va_list args;
    va_start(args, fmt);
    logLen = vsnprintf(buf, sizeof buf, fmt, args);
    va_end(args);

    if ((long unsigned int)logLen < sizeof buf) {
        outputStr = strdup(buf);
    } else {
        outputStr = (char*)malloc(logLen + 1);

        if (!outputStr) {
            printf("CRITICAL: Cannot alloc size %d for log! (Out of memory?)", logLen + 1);
            return;
        }

        va_start(args, fmt);
        vsnprintf(outputStr, logLen + 1U, fmt, args);
        va_end(args);
    }

    ofs << outputStr << "\n";

    ofs.close();

    // log it to the stdout too.
    std::cout << outputStr << "\n";

    // free the log
    free(outputStr);
}