7

When developing code, I have many console logging (std::clog) and some console output (std::cout). But now, I wanted to do online submission of my source code and I want to disable all the console logging (clog) but keep the console output (cout)

I can surely comment all of my //std::clog, but is there a better way to disable all logging inside my source file,?

Yeo
  • 11,416
  • 6
  • 63
  • 90
  • 3
    Does [this answer](http://stackoverflow.com/a/30185095/3233393) fit your problem ? – Quentin Aug 26 '16 at 07:49
  • 1
    Alternatively, `std::filebuf f; auto old = std::clog.rdbuf(&f);` at the start of main and `std::clog.rdbuf(old);` at the end can do the trick. – Johannes Schaub - litb Aug 26 '16 at 07:52
  • 1
    @Quentin it works `std::clog.setstate(std::ios_base::failbit);` remove only the `clog` messages, and still keeping the `cout`. Thanks... (can you write it as an answer). – Yeo Aug 26 '16 at 07:59
  • Anyway, how does it different from using the `ofstream.rdbuf()`, and which is better? It seems that `.setstate(std::ios_base::failbit);` is much shorter and simpler to remove clog messages than using `rdbuf` – Yeo Aug 26 '16 at 07:59
  • @Yeo I have copied over Andreas' answer as a CW. – Quentin Aug 26 '16 at 09:03
  • @Yeo Using `std::clog.setstate(std::ios_base::failbit);` should be your preferred method for what you're trying to do. The other suggestions of switching out the buffer will work also, but the stream is still going through the effort of converting values to text (e.g. float to string for display). However, setting the fail bit will prevent the stream from doing these conversions. If you know that you don't want the output, then don't go through the effort of generating the output text only to drop it. – Andrew Aug 26 '16 at 15:09

2 Answers2

7

You can redirect clog, create your own ofstream and use rdbuf function.

std::ofstream nullstream;
std::clog.rdbuf(nullstream.rdbuf());
Wiki Wang
  • 668
  • 6
  • 23
1

Copied from Andreas Papadopoulos' answer to a slightly different question -- be sure to upvote him there!


Sure, you can (example here):

int main() {
    std::clog << "First message" << std::endl;

    std::clog.setstate(std::ios_base::failbit);
    std::clog << "Second message" << std::endl;

    std::clog.clear();
    std::clog << "Last message" << std::endl;

    return 0;
}

Outputs:

First message
Last message

This is because putting the stream in fail state will make it silently discard any output, until the failbit is cleared.

Chris Jones
  • 716
  • 6
  • 11
Quentin
  • 62,093
  • 7
  • 131
  • 191
  • For the record, I have made this CW answer because the linked question is different (it also asks about restoring the stream), it is not as well presented as this one, and the accepted answer circumvents the problem instead of solving it. – Quentin Aug 26 '16 at 08:14