fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <stdexcept>
  4. #include <iomanip>
  5.  
  6. class log_error
  7. {
  8. public:
  9. log_error() = default;
  10. log_error(log_error&& other) = default;
  11. ~log_error()
  12. {
  13. // Do whatever you want with the input
  14. // Add a timestamp, process/thread id
  15. // Write it to a file, send it to a server ...
  16. std::cerr << "[ERROR] " << ss.str() << std::endl;
  17. throw std::runtime_error(ss.str());
  18. }
  19.  
  20. std::stringstream ss;
  21. };
  22.  
  23. template<typename T>
  24. log_error operator<<(log_error&& le, const T& t)
  25. {
  26. le.ss << t;
  27. return std::move(le);
  28. }
  29.  
  30. // For basic usage, you don't need a non-move operator<< / constructor.
  31. // For more complex use you may want to provide it.
  32. int main()
  33. {
  34. log_error() << "Ooops " << 23 << ", 0x" << std::setbase(16) << 23;
  35. return 0;
  36. }
Runtime error #stdin #stdout #stderr 0s 3456KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
[ERROR] Ooops 23, 0x17
terminate called after throwing an instance of 'std::runtime_error'
  what():  Ooops 23, 0x17