File: GmmLog.cpp

package info (click to toggle)
intel-gmmlib 20.4.1%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 4,524 kB
  • sloc: cpp: 52,910; ansic: 5,587; makefile: 6
file content (303 lines) | stat: -rw-r--r-- 9,633 bytes parent folder | download | duplicates (2)
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/*==============================================================================
Copyright(c) 2017 Intel Corporation

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files(the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
============================================================================*/

#include "GmmLog.h"

#if GMM_LOG_AVAILABLE
#include "Internal/Common/GmmLibInc.h"
#include "Internal/Common/GmmLogger.h"

#if _WIN32
#include <process.h>
#include <memory>
#else
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>
#include <linux/limits.h>
#endif

/// Logger instance shared by all of GmmLib within a process
GmmLib::Logger &GmmLoggerPerProc = GmmLib::Logger::CreateGmmLogSingleton();

#if _WIN32
namespace spdlog
{
    namespace sinks
    {
        /////////////////////////////////////////////////////////////////////////////////////
        /// class defines a sink which prints the messages to the debugger
        /////////////////////////////////////////////////////////////////////////////////////
        class Debugger : public sink
        {
            void log(const details::log_msg &msg) override
            {
                OutputDebugString(GMM_PREFIX_STR);
                OutputDebugString(msg.formatted.str().c_str());
            }

            void flush()
            {
            }
        };
    }
}
#endif

/////////////////////////////////////////////////////////////////////////////////////
/// Initializes Gmm Logger
///
/// @return     true if initialized successfully. false otherwise
/////////////////////////////////////////////////////////////////////////////////////
bool GmmLib::Logger::GmmLogInit()
{
    std::string LogFilePath;
    std::string ProcPath;
    std::string ProcName;
    int         Pid = 0;

// Get logging method
#if _WIN32
    uint32_t regkeyVal = 0;
    if(Utility::GmmUMDReadRegistryFullPath(GMM_LOG_REG_KEY_SUB_PATH, GMM_LOG_TO_FILE, &regkeyVal))
    {
        LogMethod = regkeyVal ? ToFile : ToOSLog;
    }

    if(Utility::GmmUMDReadRegistryFullPath(GMM_LOG_REG_KEY_SUB_PATH, GMM_LOG_LEVEL_REGKEY, &regkeyVal))
    {
        switch(static_cast<GmmLogLevel>(regkeyVal))
        {
            case Off:
                LogLevel = spdlog::level::off;
                break;
            case Trace:
                LogLevel = spdlog::level::trace;
                break;
            case Info:
                LogLevel = spdlog::level::info;
                break;
            case Error:
                LogLevel = spdlog::level::err;
                break;
        }
    }

#endif
    try
    {
        if(LogMethod == ToFile)
        {
// Get process name
#if _WIN32
            TCHAR ProcPathTChar[MAX_PATH];
            GetModuleFileName(NULL, ProcPathTChar, MAX_PATH);
            ProcPath = std::string(ProcPathTChar);

            size_t PosOfLastSlash = ProcPath.find_last_of("\\") + 1;
            size_t PosOfLastDot   = ProcPath.find_last_of(".");

            if(PosOfLastDot <= PosOfLastSlash || PosOfLastDot >= ProcPath.length() || PosOfLastSlash >= ProcPath.length())
            {
                ProcName = GMM_UNKNOWN_PROCESS;
            }
            else
            {
                ProcName = ProcPath.substr(PosOfLastSlash, PosOfLastDot - PosOfLastSlash);
            }
#else
            ProcPath = "Unknown_Proc_Path";
            ProcName = GMM_UNKNOWN_PROCESS;

            std::ifstream file;
            file.open("/proc/self/cmdline");
            if(file.is_open())
            {
                // Get process name
                getline(file, ProcPath);

                size_t PosOfLastSlash = ProcPath.find_last_of("/") + 1;
                if(PosOfLastSlash >= ProcPath.length())
                {
                    ProcName = GMM_UNKNOWN_PROCESS;
                }
                else
                {
                    // "length-1" to remove null character
                    ProcName = ProcPath.substr(PosOfLastSlash, ProcPath.length() - 1);
                }

                file.close();
            }

#endif

// Get process ID
#if _WIN32
            Pid = _getpid();
#else
            Pid = getpid();
#endif
            std::string PidStr = std::to_string(Pid);

            // TODO: Multiple GmmLib instance can be running in the same process. In that case, the file name will be
            // the same for two instances. Figure out a way to differentiate between the two instances.
            LogFilePath = std::string(GMM_LOG_FILENAME) + "_" + ProcName + "_" + PidStr;

            // Create logger
            SpdLogger = spdlog::rotating_logger_mt(GMM_LOGGER_NAME,
                                                   LogFilePath,
                                                   GMM_LOG_FILE_SIZE,
                                                   GMM_ROTATE_FILE_NUMBER);

            // Log process path
            SpdLogger->set_pattern("Process path: %v");
            SpdLogger->info(ProcPath.c_str());
        }
        else
        {
#if defined(_WIN32)
            // Log to debugger
            auto debugger_sink = std::make_shared<spdlog::sinks::Debugger>();
            SpdLogger          = std::make_shared<spdlog::logger>(GMM_LOGGER_NAME, debugger_sink);
#elif defined(__ANDROID__)
            // Log to logcat
            SpdLogger   = spdlog::android_logger(GMM_LOGGER_NAME, GMM_LOG_TAG);
#elif defined(__linux__)
            // Log to syslog
            SpdLogger = spdlog::syslog_logger(GMM_LOGGER_NAME, GMM_LOG_TAG, 1 /*Log Pid*/);
#else
            __GMM_ASSERT(0);
            return false;
#endif
        }
    }
    catch(const spdlog::spdlog_ex &ex)
    {
        __GMM_ASSERT(0);
        return false;
    }

    // Set log level
    SpdLogger->set_level(LogLevel);
    // Set log pattern
    SpdLogger->set_pattern("[%T.%e] [Thread %t] [%l] %v"); // [Time] [Thread id] [Log Level] [Text to Log]

    return true;
}

/////////////////////////////////////////////////////////////////////////////////////
/// Gmm Logger constructor
/////////////////////////////////////////////////////////////////////////////////////
GmmLib::Logger::Logger()
    : LogMethod(ToOSLog),
      LogLevel(spdlog::level::err)
{
    if(!GmmLogInit())
    {
        spdlog::set_level(spdlog::level::off);
    }
}

/////////////////////////////////////////////////////////////////////////////////////
/// Gmm Logger Destructor
/////////////////////////////////////////////////////////////////////////////////////
GmmLib::Logger::~Logger()
{
    if(SpdLogger)
    {
        SpdLogger->flush();
    }
}

/////////////////////////////////////////////////////////////////////////////////////
/// Gmm Logger C wrappers
/////////////////////////////////////////////////////////////////////////////////////
#if !_WIN32
// Linux/Android replacement for MS version of _vscprintf
inline int vscprintf_lin(const char *msg, va_list args)
{
    char    c;
    va_list args_cpy;

    // Copy `args' to prevent internal pointer modification from vsnprintf
    va_copy(args_cpy, args);
    int len = vsnprintf(&c, 1, msg, args_cpy);
    va_end(args_cpy);
    return len;
}
#endif

/////////////////////////////////////////////////////////////////////////////////////
/// Gmm Logger C wrapper for GMM_LOG_* Macros
/////////////////////////////////////////////////////////////////////////////////////
extern "C" void GMM_STDCALL GmmLibLogging(GmmLogLevel Level, const char *str, ...)
{
    va_list args;
    va_start(args, str);

#if _WIN32
    const size_t length = _vscprintf(str, args);
#else
    const size_t length = vscprintf_lin(str, args);
#endif

    char *temp = new char[length + 1];

    if(temp)
    {

#if _WIN32
        vsprintf_s(temp, length + 1, str, args);
#else
        vsnprintf(temp, length + 1, str, args);
#endif

        if(GmmLoggerPerProc.SpdLogger)
        {
            switch(Level)
            {
                case Trace:
                    // Set log level to trace if we want trace msges to be printed
                    //GmmLoggerPerProc.SpdLogger->set_level(spdlog::level::trace);
                    GmmLoggerPerProc.SpdLogger->trace(temp);
                    break;
                case Info:
                    // Set log level to info if we want info msges to be printed
                    //GmmLoggerPerProc.SpdLogger->set_level(spdlog::level::info);
                    GmmLoggerPerProc.SpdLogger->info(temp);
                    break;
                case Error:
                    GmmLoggerPerProc.SpdLogger->critical(temp);
                    break;
                default:
                    break;
            }
        }

        delete[] temp;
    }

    va_end(args);
}
#endif //#if GMM_LOG_AVAILABLE