Skip to content

Instantly share code, notes, and snippets.

@AndreLouisCaron
Created February 16, 2012 02:23
Show Gist options
  • Save AndreLouisCaron/1841061 to your computer and use it in GitHub Desktop.
Save AndreLouisCaron/1841061 to your computer and use it in GitHub Desktop.
Redirect std::cerr to log file.
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);
// ...
}
@jbmonroe
Copy link

jbmonroe commented Sep 6, 2018

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment