aboutsummaryrefslogtreecommitdiffstats
path: root/core/logging.cpp
blob: 7895679186a73773fcb15a2f0ecfe4d8bc8b7345 (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
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

#include "config.h"

#include "logging.h"

#include <cstdarg>
#include <cstdio>
#include <string>

#include "strutils.h"
#include "vector.h"


#ifdef _WIN32

#define WIN32_LEAN_AND_MEAN
#include <windows.h>

void al_print(LogLevel level, FILE *logfile, const char *fmt, ...)
{
    al::vector<char> dynmsg;
    char stcmsg[256];
    char *str{stcmsg};

    std::va_list args, args2;
    va_start(args, fmt);
    va_copy(args2, args);
    const int msglen{std::vsnprintf(str, sizeof(stcmsg), fmt, args)};
    if(unlikely(msglen >= 0 && static_cast<size_t>(msglen) >= sizeof(stcmsg)))
    {
        dynmsg.resize(static_cast<size_t>(msglen) + 1u);
        str = dynmsg.data();
        std::vsnprintf(str, dynmsg.size(), fmt, args2);
    }
    va_end(args2);
    va_end(args);

    std::wstring wstr{utf8_to_wstr(str)};
    if(gLogLevel >= level)
    {
        fputws(wstr.c_str(), logfile);
        fflush(logfile);
    }
    /* OutputDebugStringW has no 'level' property to distinguish between
     * informational, warning, or error debug messages. So only print them for
     * non-Release builds.
     */
#ifdef NDEBUG
    OutputDebugStringW(wstr.c_str());
#endif
}

#else

#ifdef __ANDROID__
#include <android/log.h>
#endif

void al_print(LogLevel level, FILE *logfile, const char *fmt, ...)
{
    al::vector<char> dynmsg;
    char stcmsg[256];
    char *str{stcmsg};

    std::va_list args, args2;
    va_start(args, fmt);
    va_copy(args2, args);
    const int msglen{std::vsnprintf(str, sizeof(stcmsg), fmt, args)};
    if(unlikely(msglen >= 0 && static_cast<size_t>(msglen) >= sizeof(stcmsg)))
    {
        dynmsg.resize(static_cast<size_t>(msglen) + 1u);
        str = dynmsg.data();
        std::vsnprintf(str, dynmsg.size(), fmt, args2);
    }
    va_end(args2);
    va_end(args);

    if(gLogLevel >= level)
    {
        std::fputs(str, logfile);
        std::fflush(logfile);
    }
#ifdef __ANDROID__
    auto android_severity = [](LogLevel l) noexcept
    {
        switch(l)
        {
        case LogLevel::Trace: return ANDROID_LOG_DEBUG;
        case LogLevel::Warning: return ANDROID_LOG_WARN;
        case LogLevel::Error: return ANDROID_LOG_ERROR;
        /* Should not happen. */
        case LogLevel::Disable:
            break;
        }
        return ANDROID_LOG_ERROR;
    };
    __android_log_print(android_severity(level), "openal", "%s", str);
#endif
}

#endif