Skip to content

Instantly share code, notes, and snippets.

@bshillingford
Created April 14, 2017 05:23
Show Gist options
  • Save bshillingford/4bc8dba3b43c3df662d7b4fa8a6e1463 to your computer and use it in GitHub Desktop.
Save bshillingford/4bc8dba3b43c3df662d7b4fa8a6e1463 to your computer and use it in GitHub Desktop.
really basic single-header C++ logging for one-off projects
#ifndef _LOG_H_
#define _LOG_H_
// logging utils
//
#include <iostream>
#include <ctime>
#define LOG(level) ::log_internal::_log_helper<::log_internal::loglevel:: level >(__FILE__, __LINE__, __FUNCTION__)
namespace log_internal {
enum loglevel {
TRACE=0,
DEBUG=10,
INFO=20,
WARN=30,
WARNING=30,
ERROR=40,
};
std::ostream& operator<<(std::ostream& os, loglevel l) {
switch (l) {
case TRACE : os << "TRACE"; break;
case DEBUG : os << "DEBUG"; break;
case INFO : os << "INFO"; break;
case WARN : os << "WARN"; break;
case ERROR : os << "ERROR"; break;
//default : os.setstate(std::ios_base::failbit);
default : os << static_cast<int>(l);
}
return os;
}
template<loglevel level>
inline std::ostream& _log_helper(const char* file, int line, const char* function) {
// log format is defined as below.
// (note: clog is not tie()'d with cout, so not autoflushed on stdout, for performance)
thread_local char ts[50];
std::time_t t = std::time(nullptr);
size_t res = std::strftime(ts, sizeof(ts), "%F %T", std::localtime(&t)); // ISO 8601 timestamp
return std::cerr << '[' << (res ? ts : "<strftime failed>") << ' ' << file << ':' << line << ' ' << function << ' ' << level << "] - ";
}
} // namespace log_internal
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment