Best way to add a "prompt" message to std::cout
c++
Solution
You could write your own class:
#include <iostream>
#include <string>
class MyLogger
{
std::ostream & out;
std::string const msg;
public:
MyLogger(std::ostream & o, std::string s)
: out(o)
, msg(std::move(s))
{ }
template <typename T>
std::ostream & operator<<(T const & x)
{
return out << msg << x;
}
};
MyLogger MyErr(std::cerr, "[LOG] ");
Usage:
MyErr << "Hello" << std::endl;
Problem
I'm searching the best way to add a custom, initial message to all the messages that `std::cout` (or `std::cerr`) prints to console/file output. For example, if I setup that this custom prompt message will be the string "[Log]", then a classic ``` std::cerr << "This is a log message" << std::endl; ``` will be printed in this way: ``` > [Log] This is a log message ``` Clearly I can obtain this behavior using ``` std::string PROMPT_MSG = "[Log]"; std::cerr << PROMPT_MSG << "This is a log message" << std::endl; ``` but I'd like a less invasive way. Thanks in advance