Skip to content

Instantly share code, notes, and snippets.

@ssell
Created December 17, 2018 23:00
Show Gist options
  • Save ssell/6773bf3c00ce1dfeb467135660404f25 to your computer and use it in GitHub Desktop.
Save ssell/6773bf3c00ce1dfeb467135660404f25 to your computer and use it in GitHub Desktop.
C++ Logger Concept
#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;
}
@ssell
Copy link
Author

ssell commented Dec 17, 2018

The above outputs:

[DEBUG] Hello World, this is a number: 100 (c:\path\to\main.cpp @ 70)

A concept for a basic logger with the following attributes:

  • Self-building, variable number of arguments. Don't have to pre-build the string.
  • Reports location of message (file and line)
  • Supports multiple report levels

Obviously there is more to be added to it, and it's not thread-safe, but it serves as a basic proof.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment