I am looking to write a logger with multiple streams for different severities of logs:
class Logger{
public:
std::ostream& errStream;
std::ostream& warnStream;
}
This way I can use the streams as such:
Logger L;
L.errStream << "This is an error message.";
L.warnStream << "This is a warning message.";
The question is, how can I overload the operator<< for each of the streams separately? Meaning I want to take different actions based on which stream is written to.
If it helps, I already have member functions for errWrite and warnWrite that take a std::string as the argument:
void errWrite(std::string);
void warnWrite(std::string);
To use these I do:
Logger L;
L.errWrite("This is an error message.");
L.warnWrite("This is a warning message.");
The trouble with these is that they are not drop in replacements for std::cout and std::cerr, which my code is already filled with. I was trying to develop something that could easily be dropped into the existing code. So ultimately I would like either:
- A way to overload the operators separately for the different members.
- An alternative approach to what I'm trying to do.
Thanks.
To overload the
operator<<
, the type needs to be different.So, to do this, you will have to make a new class to replace
std::ostream
, e.g.owarnstream
andoerrstream
.I think something like this would work:
Then you could override it using:
Just bear in mind that you will need to override ALL output operatins... It may work to do that using a template, like this: