Created
February 16, 2012 02:23
-
-
Save AndreLouisCaron/1841061 to your computer and use it in GitHub Desktop.
Redirect std::cerr to log file.
This file contains hidden or 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
namespace { | |
// redirect outputs to another output stream. | |
class redirect_outputs | |
{ | |
std::ostream& myStream; | |
std::streambuf *const myBuffer; | |
public: | |
redirect_outputs ( std::ostream& lhs, std::ostream& rhs=std::cout ) | |
: myStream(rhs), myBuffer(myStream.rdbuf()) | |
{ | |
myStream.rdbuf(lhs.rdbuf()); | |
} | |
~redirect_outputs () { | |
myStream.rdbuf(myBuffer); | |
} | |
}; | |
// redirect output stream to a string. | |
class capture_outputs | |
{ | |
std::ostringstream myContents; | |
const redirect myRedirect; | |
public: | |
capture_outputs ( std::ostream& stream=std::cout ) | |
: myContents(), myRedirect(myContents, stream) | |
{} | |
std::string contents () const | |
{ | |
return (myContents.str()); | |
} | |
}; | |
} | |
int main ( int argc, char ** argv ) | |
{ | |
// Redirect standard error stream to log file. | |
std::ofstream log_file("stde.log", std::ios::binary); | |
if (!log_file.is_open()) { | |
std::cerr | |
<< "Could not open log file for writing." | |
<< std::endl; | |
return (EXIT_FAILURE); | |
} | |
const redirect_outputs _(log_file, std::cerr); | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good stuff.
For C++11 compilers adding
redirect_outputs &operator=(const redirect_outputs &) = delete;
will clean up a compiler warning (at least for MS Visual Studio--I don't know if gcc can generate an assignment operator automagically or not).