Overload << Logging statement

Therefore, I want to use Boost.Log for all my logging purposes. Currently, I have written a class that covers all the necessary operations for creating instances and setting up helper methods.

The problem is that I want to overload the <operator to use it in cout mode. I want to be able to use it in order to have different types of arguments seems to be the biggest problem.

Here is what I tried:

 template <typename T> void trace::operator <<(T data) { std::string text=boost::lexical_cast<std::string>(data); std::cout<<data<<std::endl; BOOST_LOG_TRIVIAL(debug) << text; } 

However, I understand that this is a bit wrong logic in it. To be able to pass multiple arguments to <it must be recursive. But I'm a little confused how to do this with a buffer.

Do I need to define a logging system using a custom shell instead of a convenient boost macro? If so, does std :: ostream support return? I assume this will be the return value and the input value to the stream.

+6
source share
1 answer

If I understand your question correctly, you need to write down information about your object using the <<operator. Boost Log uses stream compatible operators, so all you need to do is define a <<statement for your class:

 class your_class_t{ public: std::string m_data; int m_value; friend std::ostream& operator<< (std::ostream& oss, your_class_t const & val) { oss<<val.m_data << ": " << val.m_value; return oss; } } 

Then you can push your class in ostream:

 your_class_t mytest; mytest.m_data = "hi"; mytest.m_value = 123; BOOST_LOG_TRIVIAL(debug) << mytest; 

You will get hi: 123

+4
source

Source: https://habr.com/ru/post/947970/


All Articles