Created
December 17, 2018 23:00
-
-
Save ssell/6773bf3c00ce1dfeb467135660404f25 to your computer and use it in GitHub Desktop.
C++ Logger Concept
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <sstream> | |
#include <iostream> | |
enum LogLevel | |
{ | |
Info = 0, | |
Debug, | |
Warning, | |
Error | |
}; | |
const std::string LogLevelNames[4] = { "INFO", "DEBUG", "WARN", "ERROR" }; | |
#define LOG_DEBUG(s, ...) Logger::Get().Log(LogLevel::Debug, __LINE__, __FILE__, s, __VA_ARGS__) | |
class Logger | |
{ | |
public: | |
static Logger& Get() | |
{ | |
static Logger instance; | |
return instance; | |
} | |
template<typename T, typename... U> | |
void Log(LogLevel const level, int line, const char* file, T first, U... args) | |
{ | |
m_CurrentMessage.str(std::string()); | |
m_CurrentMessage << "[" << LogLevelNames[level] << "] " << first; | |
BuildMessage(args...); | |
m_CurrentMessage << " (" << file << " @ " << line << ") "; | |
if (level == LogLevel::Debug) | |
{ | |
#ifdef _DEBUG | |
std::cout << m_CurrentMessage.str() << std::endl; | |
#endif | |
} | |
else | |
{ | |
std::cout << m_CurrentMessage.str() << std::endl; | |
} | |
} | |
protected: | |
private: | |
template<typename T, typename... U> | |
void BuildMessage(T first, U... last) | |
{ | |
m_CurrentMessage << first; | |
BuildMessage(last...); | |
} | |
void BuildMessage() | |
{ | |
} | |
std::stringstream m_CurrentMessage; | |
}; | |
int main() | |
{ | |
LOG_DEBUG("Hello World, this is a number: ", 100); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The above outputs:
A concept for a basic logger with the following attributes:
Obviously there is more to be added to it, and it's not thread-safe, but it serves as a basic proof.