forked from KhronosGroup/OpenXR-SDK-Source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.cpp
61 lines (51 loc) · 2 KB
/
logger.cpp
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
// Copyright (c) 2017-2023, The Khronos Group Inc.
//
// SPDX-License-Identifier: Apache-2.0
#include "pch.h"
#include "logger.h"
#include <sstream>
#if defined(ANDROID)
#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, "hello_xr", __VA_ARGS__)
#define ALOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, "hello_xr", __VA_ARGS__)
#endif
namespace {
Log::Level g_minSeverity{Log::Level::Info};
std::mutex g_logLock;
} // namespace
namespace Log {
void SetLevel(Level minSeverity) { g_minSeverity = minSeverity; }
void Write(Level severity, const std::string& msg) {
if (severity < g_minSeverity) {
return;
}
const auto now = std::chrono::system_clock::now();
const time_t now_time = std::chrono::system_clock::to_time_t(now);
tm now_tm;
#ifdef _WIN32
localtime_s(&now_tm, &now_time);
#else
localtime_r(&now_time, &now_tm);
#endif
// time_t only has second precision. Use the rounding error to get sub-second precision.
const auto secondRemainder = now - std::chrono::system_clock::from_time_t(now_time);
const int64_t milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(secondRemainder).count();
static std::map<Level, const char*> severityName = {
{Level::Verbose, "Verbose"}, {Level::Info, "Info "}, {Level::Warning, "Warning"}, {Level::Error, "Error "}};
std::ostringstream out;
out.fill('0');
out << "[" << std::setw(2) << now_tm.tm_hour << ":" << std::setw(2) << now_tm.tm_min << ":" << std::setw(2) << now_tm.tm_sec
<< "." << std::setw(3) << milliseconds << "]"
<< "[" << severityName[severity] << "] " << msg << std::endl;
std::lock_guard<std::mutex> lock(g_logLock); // Ensure output is serialized
((severity == Level::Error) ? std::clog : std::cout) << out.str();
#if defined(_WIN32)
OutputDebugStringA(out.str().c_str());
#endif
#if defined(ANDROID)
if (severity == Level::Error)
ALOGE("%s", out.str().c_str());
else
ALOGV("%s", out.str().c_str());
#endif
}
} // namespace Log