I am writing my own logger. Hoping to gain some performance, I added a piece of code to control the number of flushes to std::ofstream
. To do this, I used a temporary buffer
of type std::stringstream
. The log operations are written into this buffer first and then flushed into the std::ofstream
in the right time. (look at void flushLog()
) :
#include<iostream>
#include<sstream>
#include<fstream>
class BasicLogger
{
std::stringstream out;
std::ofstream logFile;
typedef std::basic_ostream<char, std::char_traits<char> > CoutType;
typedef CoutType& (*StandardEndLine)(CoutType&);
public:
BasicLogger(std::string id_){
std::string path = id_ + ".txt";
if(path.size()){
logFile.open(path.c_str());
if ((logFile.is_open() && logFile.good())){
}
}
}
BasicLogger& operator<<(StandardEndLine manip) {
std::cout << "Blogger:call to cout type oprtor" << std::endl;
manip(out);
return *this;
}
template <typename T>
BasicLogger & operator<< (const T& val)
{
std::cout << "Blogger:call to oprtor" << std::endl;
out << val;
if(out.tellp() > 512000/*500KB*/){// by some googling this estimated hardcode value promises less cycles to write to a file
flushLog();
}
return *this;
}
void flushLog()
{
if ((logFile.is_open() && logFile.good()))
{
logFile << out.str();
logFile.flush();
out.str(std::string());
}
}
};
coming to know std::ofstream
already has its own buffer, I need to rethink if manipulating the buffer was a right thing to do. ??