if I want to create a logging class, say
class logging_class {
public:
std::ofstream error;
std::ofstream event;
logging_class() {}
logging_class(string err, string evt) {
error.open(err);
event.open(evt);
}
~logging_class() {
error.close();
event.close();
}
};
so that later I can easily create program log:
logging_class logger("Log_Error.txt","Log_Event.txt");
logger.error << "something wrong";
logger.event << "something interesting";
Now, at the early stage of development, I want to redirect all the output to screen (i.e. std::cout). I don't want to change the usage of logger.error<<"something wrong";
to std::cout<<"something wrong";
, because later I will need to change all instances of std::cout
to either logger.error
or logger.event
(maybe thousands of them). Can I make some easy changes in the class logger to do this?
Update: Following Enlico's instruction, I can modify the logging_class
as:
class logging_class {
public:
//std::ofstream error;
//std::ofstream event;
std::ostream& error;
std::ostream& event;
logging_class():error(std::cout),event(std::cout) {}
//logging_class(string err, string evt) {
// error.open(err);
// event.open(evt);
//}
//~logging_class() {
// error.close();
// event.close();
//}
};
and after creating object with default constructor:
logging_class logger;
I can now redirect all the logging to screen display.