Last active
January 23, 2021 18:18
-
-
Save xkortex/2fdb3feb083e73fc832170971fca5cde to your computer and use it in GitHub Desktop.
Header lib for simplified godbolt logging
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
/* | |
* File: Log.h | |
* Based on https://stackoverflow.com/a/17605306/ by manu343726 | |
* https://github.com/Manu343726/Cpp11CustomLogClass | |
* Author: xkortex | |
* Stackoverflow code snipets are licensed under cc-wiki | |
*/ | |
#ifndef LOG_H | |
#define LOG_H | |
#include <iostream> | |
#include <ctime> | |
#include <string> | |
static std::string isonow(void) { | |
struct timespec ts; | |
timespec_get(&ts, TIME_UTC); | |
char buf_sec[32]; | |
char buf_frac[16]; | |
// %Y-%m-%d | |
strftime(buf_sec, sizeof(buf_sec), "%H:%M:%S", gmtime(&ts.tv_sec)); | |
double fracs = ((double) ts.tv_nsec ) / 1e9; | |
sprintf(buf_frac, "%0.6lf", fracs); | |
return std::string(buf_sec) + std::string(buf_frac).substr(1); | |
} | |
class Log | |
{ | |
private: | |
std::ostream& _out_stream; | |
bool _next_is_begin; | |
const std::string _spacer; | |
using endl_type = std::ostream&(std::ostream&); //This is the key: std::endl is a template function, and this is the signature of that function (For std::ostream). | |
public: | |
Log(std::ostream& out_stream) : _spacer(""), _out_stream( out_stream ) , _next_is_begin( true ) {} | |
Log(const std::string& spacer ="", std::ostream& out_stream = std::cout) : | |
_spacer(spacer), _out_stream( out_stream ) , _next_is_begin( true ) {} | |
//Overload for std::endl only: | |
Log& operator<<(endl_type endl) { | |
_next_is_begin = true; | |
_out_stream << endl; | |
return *this; | |
} | |
//Overload for anything else: | |
template<typename T> | |
Log& operator<< (const T& data) { | |
if( _next_is_begin ) | |
_out_stream << isonow() << ": " << data; | |
else | |
_out_stream << _spacer << data; | |
_next_is_begin = false; | |
return *this; | |
} | |
}; | |
#endif /* LOG_H */ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment