Skip to content

Instantly share code, notes, and snippets.

@hoxnox
Created October 24, 2015 18:43
Show Gist options
  • Save hoxnox/306728bc7ee60b772bdb to your computer and use it in GitHub Desktop.
Save hoxnox/306728bc7ee60b772bdb to your computer and use it in GitHub Desktop.
Simple logger for C++ (prefix + suffix)
/**@author Merder Kim <hoxnox@gmail.com>
* @date 20151024 22:21:01
Usage:
SIMPLE_LOGGER_INIT
int main()
{
SIMPLE_LOGGER_SET_VERBOSE;
SIMPLE_LOGGER_SET_ALIGN;
ILOG << "Hello, world!" << std::endl
<< "From the next line";
VLOG << "Verbosity";
}
*/
#ifndef __SIMPLE_LOGGER
#define __SIMPLE_LOGGER
#include <sstream>
#include <iostream>
#include <memory>
class SimpleLogStream
{
public:
static SimpleLogStream* GetInstance()
{
if (!instance_)
instance_.reset(new SimpleLogStream());
return instance_.get();
}
std::stringstream& _stream(std::ostream& ostr)
{
ostr_ = &ostr;
ss_.str("");
memset(prefix_buf_, 0, sizeof(prefix_buf_));
time_t t = time(NULL);
strftime(prefix_buf_, sizeof(prefix_buf_) - 1, "[%Y%m%dT%H%M%S] ", localtime(&t));
prefix_len_ = strlen(prefix_buf_);
ss_ << prefix_buf_;
return ss_;
}
SimpleLogStream& operator< (std::ostream& ss)
{
if (align)
{
std::istream strm(ss.rdbuf());
bool first = true;
for(std::string line; std::getline(strm, line);)
{
if (first)
{
first = false;
}
else
{
for(size_t i = 0; i < prefix_len_; ++i)
*ostr_ << ' ';
}
*ostr_ << line << std::endl;
}
}
else
{
*ostr_ << ss.rdbuf() << std::endl;
}
return *this;
}
static bool verbose;
static bool align;
private:
static std::unique_ptr<SimpleLogStream> instance_;
SimpleLogStream() : ostr_(&std::cout) {};
SimpleLogStream(const SimpleLogStream&) = delete;
SimpleLogStream(const SimpleLogStream&&) = delete;
SimpleLogStream& operator=(const SimpleLogStream&) = delete;
std::stringstream ss_;
std::ostream* ostr_;
char prefix_buf_[20];
uint8_t prefix_len_;
};
class SilentNoop{
public:
SilentNoop() { }
void operator&(SimpleLogStream&) { }
};
#define VLOG !SimpleLogStream::GetInstance()->verbose ? (void)0 : SilentNoop() & *SimpleLogStream::GetInstance() < SimpleLogStream::GetInstance()->_stream(std::cout)
#define ILOG SilentNoop() & *SimpleLogStream::GetInstance() < SimpleLogStream::GetInstance()->_stream(std::cout)
#define ELOG SilentNoop() & *SimpleLogStream::GetInstance() < SimpleLogStream::GetInstance()->_stream(std::cerr)
#define SIMPLE_LOGGER_INIT std::unique_ptr<SimpleLogStream> SimpleLogStream::instance_; bool SimpleLogStream::verbose = false; bool SimpleLogStream::align = false;
#define SIMPLE_LOGGER_SET_VERBOSE SimpleLogStream::verbose = true;
#define SIMPLE_LOGGER_SET_ALIGN SimpleLogStream::align = true;
#endif // guard
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment