Skip to content

Instantly share code, notes, and snippets.

@pezcode
Created January 14, 2018 14:58
Show Gist options
  • Save pezcode/315a8ca9c33195e8c88a295edd9d85e2 to your computer and use it in GitHub Desktop.
Save pezcode/315a8ca9c33195e8c88a295edd9d85e2 to your computer and use it in GitHub Desktop.
simple C++ iostream log
#pragma once
#include <ostream>
#include <fstream>
using namespace std;
class Log
{
typedef std::ostream& (*ostream_manipulator)(std::ostream&);
public:
enum eLevel { Debug, Error, Info };
Log(ostream& m_stream) : stream(m_stream), level(Info) { }
template<typename T> void log(const T& v)
{
switch(level)
{
case Debug:
#ifdef DEBUG
stream << "DEBUG: " << v;
#endif
break;
case Error:
stream << "ERROR: " << v;
break;
case Info:
stream << v;
break;
}
}
template<typename T> Log& operator<<(const T& v)
{
log(v);
return *this;
}
// allow manipulators for the stream (endl, ...)
Log& operator<<(ostream_manipulator pf)
{
stream << pf;
return *this;
}
Log& operator<<(eLevel l) { level = l; }
protected:
ostream& stream;
eLevel level;
};
class FileLog : Log
{
public:
FileLog(const string& filename) : file(filename.c_str(), ios::out | ios::ate), Log(file) { }
private:
ofstream file;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment