7

So I want to use Boost.Log for all my logging purposes. I currently wrote a class that encompasses all the required operations of instantiating and setting up helper methods.

Problem is that I want to overload the << operator to use it in a cout manner. I want to be able to use it for having different argument types seems to be the biggest issue.

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 this is a little flawed in it's logic. To be able to pass multiple args to << it needs to be recursive. But I am a little confused how I would do this with boost log.

Do I have to define the log system with a custom sink instead of the convenient boost macro? If so does this support std::ostream returns? I'm guessing this would be the return value and the input value into the stream.

1
  • I want to be able to use this in a custom object. I have multiple threads for which I want their own 'logging' object.
    – bge0
    Jun 24, 2013 at 6:50

1 Answer 1

5

if I understand your question correctly, you need to log information about your object using << operator. Boost Log uses ostream-compatible operators, so all you need is to define << operator 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'll get hi: 123

1
  • 1
    Note: STL != C++ standard library. The STL also never contained iostream functionality.
    – Aleph
    Nov 9, 2013 at 11:27

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.