I want to make a Logger that can be used like std::cout
, but I want to log some extra data like date, time, __LINE__
, __func__
, and __FILE__
which should be saved to the file automatically.
Example
ToolLogger log;
log << "some data" << std::endl;
Expected output
[14.11.2015 21:10:12.344 (main.cpp) (main,14): some data
Inadequate solution
To do this I have to put macros like __LINE__
direct in the line where I call my logger, otherwise the macros won't work correct. I found that I can replace std::endl
with my macro that will do this black magic like this:
#define __FILENAME__ (strrchr(__FILE__,'/') ? strrchr(__FILE__,'/') + 1 : __FILE__)
#define logendl \
((ToolLogger::fileName = __FILENAME__).empty() ? "" : "") \
<< ((ToolLogger::line = __LINE__) ? "" : "") \
<< ((ToolLogger::function = __func__).empty() ? "" : "") \
<< std::endl
The macro logendl
uses static variables from my ToolLogger
class to save the values of __LINE__
, __func__
and __FILE__
needed later. So actually using the logger will looks like this:
ToolLogger log;
log << "some data" << logendl;
In the class i have to overload the operator<<
to get this to work, and I need two of them. One for taking the normal values like std::string
or int
, and the other to take the std::endl
manipulator. Here is the most important things from my class:
class ToolLogger
{
public:
// standard operator<< //
template<typename T>
ToolLogger& operator<< (const T& str)
{
out << str;
return *this;
}
// operator<< for taking the std::endl manipulator //
typedef std::basic_ostream<char, std::char_traits<char> > CoutType;
typedef CoutType& (*StandardEndLine)(CoutType&);
ToolLogger& operator<<(StandardEndLine manip)
{
// save fileName, line and function to the file //
// and all what is already in stringstream //
// clear stringstream //
return *this;
}
static string fileName;
static int line;
static string function;
private:
ofstream file;
std::stringstream out;
};
string ToolLogger::fileName;
int ToolLogger::line;
string ToolLogger::function;
Problem
The problem in this solution is that I can use my logger in two ways:
log << "some data" << logendl; // correct //
log << "some data" << std::endl; // compiles -> wrong /
So actually I need to remove the operator<<
from my class that takes std::endl
manipulator, and solve it other way, but how to do it? I was thinking about changing std::endl
in logendl
macro to other custom manipulator, and then this custom manipulator will do the work that is actually doing the operator<<
, but I have no idea how to do it. I'm looking for other solution, any suggestions?