utility 2026.1.9
A comprehensive C++ utilities library tailored for the development of modern desktop and extended reality (XR) applications.
Loading...
Searching...
No Matches
logger.cpp
1/*
2 Copyright (c) 2026 ETIB Corporation
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in
6 the Software without restriction, including without limitation the rights to
7 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 of the Software, and to permit persons to whom the Software is furnished to do
9 so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22
23#include <algorithm>
24#include <cctype>
25#include <chrono>
26#include <cstdlib>
27#include <ctime>
28#include <limits>
29#include <iomanip>
30#include <mutex>
31
33
34namespace utility::logging
35{
36
37 namespace
38 {
45 LogLevel parseLevel(const char *text, LogLevel fallback)
46 {
47 if (text == nullptr) {
48 return fallback;
49 }
50 std::string value(text);
51 std::transform(value.begin(), value.end(), value.begin(),
52 [](unsigned char c) {
53 return static_cast<char>(std::tolower(c));
54 });
55 if (value == "debug") {
56 return LogLevel::DEBUG_LEVEL;
57 }
58 if (value == "info") {
59 return LogLevel::INFO_LEVEL;
60 }
61 if (value == "warning") {
62 return LogLevel::WARNING_LEVEL;
63 }
64 if (value == "error") {
65 return LogLevel::ERROR_LEVEL;
66 }
67 return fallback;
68 }
69 } // namespace
70
72 {
73 switch (level) {
74 case LogLevel::DEBUG_LEVEL:
75 return "Debug";
76 case LogLevel::INFO_LEVEL:
77 return "Info";
78 case LogLevel::WARNING_LEVEL:
79 return "Warning";
80 case LogLevel::ERROR_LEVEL:
81 return "Error";
82 default:
83 return "Unknown";
84 }
85 }
86
88 {
89 auto now = std::chrono::system_clock::now();
90 auto time = std::chrono::system_clock::to_time_t(now);
91 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
92 now.time_since_epoch())
93 % 1000;
94
95 std::tm local {};
96#if defined(_WIN32)
97 localtime_s(&local, &time);
98#else
99 localtime_r(&time, &local);
100#endif
101
102 // Format into a stack buffer instead of a `std::stringstream`: this
103 // leaves a single allocation (the returned string), none for the
104 // formatting. The millisecond field is zero-padded to three digits.
105 char buffer[32];
106 std::size_t length =
107 std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &local);
108 const int millis = static_cast<int>(ms.count());
109 buffer[length++] = '.';
110 buffer[length++] = static_cast<char>('0' + (millis / 100) % 10);
111 buffer[length++] = static_cast<char>('0' + (millis / 10) % 10);
112 buffer[length++] = static_cast<char>('0' + millis % 10);
113 return std::string(buffer, length);
114 }
115
116 Logger::Logger(const std::string &name)
117 : _name(name)
118 {
119 // Allow deployments to restore verbosity without a recompile.
120 const char *envLevel = std::getenv("UTILITY_LOG_LEVEL");
121 if (envLevel != nullptr) {
122 _minLevel.store(
123 parseLevel(envLevel,
124 _minLevel.load(std::memory_order_relaxed)),
125 std::memory_order_relaxed);
126 }
127 }
128
129 void Logger::setMinLevel(LogLevel level) noexcept
130 {
131 _minLevel.store(level, std::memory_order_relaxed);
132 }
133
134 LogLevel Logger::getMinLevel(void) const noexcept
135 {
136 return _minLevel.load(std::memory_order_relaxed);
137 }
138
140 {
141 _flushPolicy.store(policy, std::memory_order_relaxed);
142 }
143
145 {
146 return _flushPolicy.load(std::memory_order_relaxed);
147 }
148
149} // namespace utility::logging
LogLevel getMinLevel(void) const noexcept
Get the current minimum log level.
Definition logger.cpp:134
FlushPolicy getFlushPolicy(void) const noexcept
Get the current output flush policy.
Definition logger.cpp:144
void setMinLevel(LogLevel level) noexcept
Set the minimum log level. Messages below this level are suppressed.
Definition logger.cpp:129
Logger(const std::string &name)
Default constructor.
Definition logger.cpp:116
static std::string levelToString(LogLevel level)
Get string representation of log level.
Definition logger.cpp:71
void setFlushPolicy(FlushPolicy policy) noexcept
Set the output flush policy.
Definition logger.cpp:139
static std::string getTimestamp(void)
Get current timestamp as formatted string.
Definition logger.cpp:87
Logging interface with levels, source-location metadata, and stream-style output.
FlushPolicy
Controls when a stream-backed logger flushes its output.
Definition logger.hpp:68
LogLevel
Log severity levels.
Definition logger.hpp:54