2018-08-03 09:19:12 +00:00
|
|
|
#ifndef DEBUG_LOG_H
|
|
|
|
#define DEBUG_LOG_H
|
|
|
|
|
|
|
|
#include <mutex>
|
|
|
|
#include <iostream>
|
|
|
|
|
|
|
|
namespace Debug
|
|
|
|
{
|
|
|
|
enum Level
|
|
|
|
{
|
|
|
|
Error = 1,
|
|
|
|
Warning = 2,
|
|
|
|
Info = 3,
|
|
|
|
Verbose = 4,
|
2018-11-01 10:08:33 +00:00
|
|
|
Debug = 5,
|
|
|
|
Marker = Debug,
|
2018-10-12 10:11:41 +00:00
|
|
|
|
2018-11-01 10:08:33 +00:00
|
|
|
NoLevel = 6 // Do not filter messages in this case
|
2018-08-03 09:19:12 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
extern Level CurrentDebugLevel;
|
|
|
|
}
|
|
|
|
|
|
|
|
class Log
|
|
|
|
{
|
|
|
|
static std::mutex sLock;
|
|
|
|
|
|
|
|
std::unique_lock<std::mutex> mLock;
|
|
|
|
public:
|
2021-11-07 18:47:02 +00:00
|
|
|
explicit Log(Debug::Level level)
|
|
|
|
: mShouldLog(level <= Debug::CurrentDebugLevel)
|
2018-08-03 09:19:12 +00:00
|
|
|
{
|
2021-11-07 18:47:02 +00:00
|
|
|
// No need to hold the lock if there will be no logging anyway
|
|
|
|
if (!mShouldLog)
|
|
|
|
return;
|
|
|
|
|
|
|
|
// Locks a global lock while the object is alive
|
2022-05-08 20:43:30 +00:00
|
|
|
mLock = lock();
|
2021-11-07 18:47:02 +00:00
|
|
|
|
2018-10-12 10:11:41 +00:00
|
|
|
// If the app has no logging system enabled, log level is not specified.
|
|
|
|
// Show all messages without marker - we just use the plain cout in this case.
|
|
|
|
if (Debug::CurrentDebugLevel == Debug::NoLevel)
|
|
|
|
return;
|
|
|
|
|
2021-11-07 18:47:02 +00:00
|
|
|
std::cout << static_cast<unsigned char>(level);
|
2018-08-03 09:19:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Perfect forwarding wrappers to give the chain of objects to cout
|
|
|
|
template<typename T>
|
|
|
|
Log& operator<<(T&& rhs)
|
|
|
|
{
|
2021-11-07 18:47:02 +00:00
|
|
|
if (mShouldLog)
|
2018-08-03 09:19:12 +00:00
|
|
|
std::cout << std::forward<T>(rhs);
|
|
|
|
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
|
|
|
~Log()
|
|
|
|
{
|
2021-11-07 18:47:02 +00:00
|
|
|
if (mShouldLog)
|
2018-08-03 09:19:12 +00:00
|
|
|
std::cout << std::endl;
|
|
|
|
}
|
|
|
|
|
2022-05-08 20:43:30 +00:00
|
|
|
static std::unique_lock<std::mutex> lock() { return std::unique_lock<std::mutex>(sLock); }
|
|
|
|
|
2018-08-03 09:19:12 +00:00
|
|
|
private:
|
2021-11-07 18:47:02 +00:00
|
|
|
const bool mShouldLog;
|
2018-08-03 09:19:12 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
#endif
|