cppcore
A small, portable C++ core library
Loading...
Searching...
No Matches
Logger.cpp
Go to the documentation of this file.
1/*-----------------------------------------------------------------------------------------------
2The MIT License (MIT)
3
4Copyright (c) 2014-2025 Kim Kulling
5
6Permission is hereby granted, free of charge, to any person obtaining a copy of
7this software and associated documentation files (the "Software"), to deal in
8the Software without restriction, including without limitation the rights to
9use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
10the Software, and to permit persons to whom the Software is furnished to do so,
11subject to the following conditions:
12
13The above copyright notice and this permission notice shall be included in all
14copies or substantial portions of the Software.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
18FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
19COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22-----------------------------------------------------------------------------------------------*/
25
26#include <cassert>
27#include <iomanip>
28#include <iostream>
29#include <sstream>
30#include <string>
31
32namespace cppcore {
33namespace {
34 void appendDomain(const String &domain, String &logMsg) {
35 if (!domain.isEmpty()) {
36 logMsg += '(';
37 logMsg += domain;
38 logMsg += ')';
39 }
40 }
41
42 ::std::string stripFilename(const ::std::string &filename) {
43 if (filename.empty()) {
44 return filename;
45 }
46
47 ::std::string::size_type pos = filename.find_last_of("/");
48 if (pos == ::std::string::npos) {
49 return filename;
50 }
51 const ::std::string strippedName = filename.substr(pos + 1, filename.size() - pos - 1);
52
53 return strippedName;
54 }
55
56 void addTraceInfo(const String &file, int line, String &msg) {
57 if (Logger::getInstance()->getVerboseMode() == Logger::VerboseMode::Trace) {
58 msg += String(" (", 2);
59 std::string stripped = stripFilename(file.c_str());
60 msg += String(stripped.c_str(), stripped.size());
61 msg += String(", ", 2);
62 std::stringstream ss;
63 ss << line;
64 std::string lineno = ss.str();
65 msg += String(lineno.c_str(), lineno.size());
66 msg += ')';
67 }
68 }
69}
70
72 mIsActive = true;
73}
74
76 mIsActive = false;
77}
78
80 return mIsActive;
81}
82
83Logger *Logger::sLogger = nullptr;
84
85Logger *Logger::create() {
86 if (sLogger == nullptr) {
87 sLogger = new Logger;
88 }
89
90 return sLogger;
91}
92
93void Logger::set(Logger *logger) {
94 if (logger == sLogger) {
95 return;
96 }
97 kill();
98 sLogger = logger;
99}
100
102 if (sLogger == nullptr) {
103 static_cast<void>(create());
104 }
105
106 return sLogger;
107}
108
110 if (sLogger != nullptr) {
111 delete sLogger;
112 sLogger = nullptr;
113 }
114}
115
117 mVerboseMode = sev;
118}
119
121 return mVerboseMode;
122}
123
124void Logger::trace(const String &domain, const String &msg) {
126 String logMsg;
127 logMsg += String("Trace: ", 6);
128 logMsg += msg;
129 appendDomain(domain, logMsg);
130
131 print(logMsg);
132 }
133}
134
135void Logger::debug(const String &domain, const String &msg) {
137 String logMsg;
138 logMsg += String("Dbg: ", 6);
139 logMsg += msg;
140 appendDomain(domain, logMsg);
141
142 print(logMsg);
143 }
144}
145
146void Logger::info(const String &domain, const String &msg) {
151 String logMsg;
152
153 logMsg += String("Info: ", 6);
154 logMsg += msg;
155
156 appendDomain(domain, logMsg);
157
158 print(logMsg);
159 }
160}
161
162void Logger::print(const String &msg, PrintMode mode) {
163 if (msg.isEmpty()) {
164 return;
165 }
166
167 if (msg.size() > 8 && msg[6] == '<' && msg[7] == '=') {
168 mIntention -= 2;
169 }
170
171 String logMsg;
172 if (0 != mIntention) {
173 for (uint32_t i = 0; i < mIntention; i++) {
174 logMsg += ' ';
175 }
176 }
177
178 logMsg += msg;
179 if (PrintMode::WithDateTime == mode) {
180 logMsg += String(" (", 2);
181 logMsg += this->getDateTime();
182 logMsg += ')';
183 }
184
185 logMsg += String(" \n", 2);
186 for (size_t i = 0; i < mLogStreams.size(); ++i) {
187 AbstractLogStream *stream = mLogStreams[i];
188 if (stream != nullptr) {
189 stream->write(logMsg);
190 }
191 }
192
193 if (msg.size() > 8 && msg[6] == '=' && msg[7] == '>') {
194 mIntention += 2;
195 }
196}
197
198void Logger::warn(const String &domain, const String &msg) {
199 String logMsg;
200 logMsg += String("Warn: ", 6);
201 logMsg += msg;
202 appendDomain(domain, logMsg);
203
204 print(logMsg);
205}
206
207void Logger::error(const String &domain, const String &msg) {
208 String logMsg;
209 logMsg += String("Err: ", 6);
210 logMsg += msg;
211 appendDomain(domain, logMsg);
212
213 print(logMsg);
214}
215
216void Logger::fatal(const String &domain, const String &msg) {
217 String logMsg;
218 logMsg += String("Fatal:", 6);
219 logMsg += msg;
220 appendDomain(domain, logMsg);
221
222 print(logMsg);
223}
224
226 if (nullptr == pLogStream) {
227 return;
228 }
229
230 mLogStreams.add(pLogStream);
231}
232
234 if (nullptr == logStream) {
235 return;
236 }
237
238 for (size_t i = 0; i < mLogStreams.size(); ++i) {
239 if (mLogStreams[i] == logStream) {
240 delete mLogStreams[i];
241 mLogStreams.remove(i);
242 }
243 }
244}
245
246Logger::Logger() {
247 mLogStreams.add(new StdLogStream);
248}
249
250Logger::~Logger() {
251 for (size_t i = 0; i < mLogStreams.size(); ++i) {
252 delete mLogStreams[i];
253 }
254}
255
256String Logger::getDateTime() const {
257 static constexpr uint32_t Space = 2;
258 DateTime currentDateTime;
259 std::stringstream stream;
260 stream.fill('0');
261 stream << std::setw(Space) << currentDateTime.year << "."
262 << std::setw(Space) << currentDateTime.month << "."
263 << std::setw(Space * 2) << currentDateTime.day << " "
264 << std::setw(Space) << currentDateTime.hour << ":"
265 << std::setw(Space) << currentDateTime.minute << ":"
266 << std::setw(Space) << currentDateTime.second;
267 const std::string tmp(stream.str());
268 String dateTime(tmp.c_str(), tmp.size());
269 return dateTime;
270}
271
272void Logger::StdLogStream::write(const String &msg) {
273 std::cout << msg.c_str();
274}
275
276void tracePrint(const String &domain, const String &file, int line, const String &msg) {
277 String message;
278 message += msg;
279 addTraceInfo(file, line, message);
280 Logger::getInstance()->trace(domain, message);
281}
282
283void debugPrint(const String &domain, const String &file, int line, const String &msg) {
284 String message;
285 message += msg;
286 addTraceInfo(file, line, message);
287 Logger::getInstance()->debug(domain, message);
288}
289
290void infoPrint(const String &domain, const String &file, int line, const String &msg) {
291 String message;
292 message += msg;
293 addTraceInfo(file, line, message);
294 Logger::getInstance()->info(domain, message);
295}
296
297void warnPrint(const String &domain, const String &file, int line, const String &message) {
298 String msg;
299 msg += message;
300 addTraceInfo(file, line, msg);
301 Logger::getInstance()->warn(domain, msg);
302}
303
304void errorPrint(const String &domain, const String &file, int line, const String &message) {
305 String msg;
306 msg += message;
307 addTraceInfo(file, line, msg);
308 Logger::getInstance()->error(domain, msg);
309}
310
311void fatalPrint(const String &domain, const String &file, int line, const String &message) {
312 String msg;
313 msg += message;
314 addTraceInfo(file, line, msg);
315 Logger::getInstance()->fatal(domain, msg);
316}
317
318} // namespace cppcore
319
This pure abstract interface class declares the protocol for log-stream implementation.
Definition Logger.h:46
virtual void deactivate()
The stream will be deactivated.
Definition Logger.cpp:75
virtual bool isActive() const
Returns true, if the stream is active.
Definition Logger.cpp:79
virtual void write(const String &message)=0
Will write a message into the attached log stream.
virtual void activate()
The stream will be activated.
Definition Logger.cpp:71
This class implements a simple logger.
Definition Logger.h:88
void setVerboseMode(VerboseMode sev)
Set the severity of the logger.
Definition Logger.cpp:116
VerboseMode
Describes the verbose mode.
Definition Logger.h:91
@ Normal
Only warnings and errors will be logged.
Definition Logger.h:93
@ Debug
All debug messages will be logged as well.
Definition Logger.h:95
@ Verbose
Normal messages will be logged as well.
Definition Logger.h:94
@ Trace
Will enable the tracing.
Definition Logger.h:96
void unregisterLogStream(const AbstractLogStream *pLogStream)
Unregisters a registered log stream.
Definition Logger.cpp:233
static Logger * getInstance()
returns the singleton instance pointer of the logger.
Definition Logger.cpp:101
void info(const String &domain, const String &msg)
Logs an info message.
Definition Logger.cpp:146
static void set(Logger *logger)
Will set a user-defined logger instance.
Definition Logger.cpp:93
static void kill()
Kills the only instance of the logger.
Definition Logger.cpp:109
PrintMode
Describes the mode for prints into the active log stream.
Definition Logger.h:101
@ WithDateTime
A dateTime string will put be in front of the entry.
Definition Logger.h:103
void trace(const String &domain, const String &msg)
Logs a trace message.
Definition Logger.cpp:124
void warn(const String &domain, const String &msg)
Logs a warn message.
Definition Logger.cpp:198
void print(const String &message, PrintMode mode=PrintMode::WithoutDateTime)
Logs a print message.
Definition Logger.cpp:162
void debug(const String &domain, const String &msg)
Logs a debug message.
Definition Logger.cpp:135
void error(const String &domain, const String &msg)
Logs a error message.
Definition Logger.cpp:207
static Logger * create()
Creates the unique logger instance and returns a pointer showing to it.
Definition Logger.cpp:85
VerboseMode getVerboseMode() const
Returns the current severity of the logger.
Definition Logger.cpp:120
void fatal(const String &domain, const String &msg)
Logs a fatal error message.
Definition Logger.cpp:216
void registerLogStream(AbstractLogStream *pLogStream)
Registers a new log stream.
Definition Logger.cpp:225
size_t size() const
The current size of the array will be returned.
Definition TArray.h:423
void add(const T &newValue)
A new item will be added to the array.
Definition TArray.h:210
size_t size() const
Returns the size of the string buffer.
bool isEmpty() const
Will return true, if the string is empty.
TStringBase< char > String
Definition Logger.h:34
void tracePrint(const String &domain, const String &file, int line, const String &msg)
Definition Logger.cpp:276
void errorPrint(const String &domain, const String &file, int line, const String &msg)
Definition Logger.cpp:304
void warnPrint(const String &domain, const String &file, int line, const String &msg)
Definition Logger.cpp:297
void debugPrint(const String &domain, const String &file, int line, const String &msg)
Definition Logger.cpp:283
void fatalPrint(const String &domain, const String &file, int line, const String &msg)
Definition Logger.cpp:311
void infoPrint(const String &domain, const String &file, int line, const String &msg)
Definition Logger.cpp:290