Question

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.

Était-ce utile?

La solution

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top