Overloading << Operator for Boost Logging Object
Asked Answered
M

1

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.

Morissa answered 24/6, 2013 at 6:47 Comment(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.Morissa
S
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

Sinner answered 9/11, 2013 at 10:11 Comment(1)
Note: STL != C++ standard library. The STL also never contained iostream functionality.Prink

© 2022 - 2024 — McMap. All rights reserved.