Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading << Operator for Boost Logging Object

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.

like image 376
bge0 Avatar asked Jun 24 '13 06:06

bge0


People also ask

Can we overload << operator?

We can overload the '>>' and '<<' operators to take input in a linked list and print the element in the linked list in C++. It has the ability to provide the operators with a special meaning for a data type, this ability is known as Operator Overloading.

Can we overload << operator in C++?

You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions. An overloaded operator is called an operator function.

What is the advantage of overloading the << and >> operators?

By overloading the operators, we can give additional meaning to the operators like +-*/=.,= etc., which by default are supposed to work only on standard data types like int, float, char, void etc. It is an essential concept in C++.

What is boost logging?

Boost. Log, part of collection of the Boost C++ Libraries, provides tools for adding logging to libraries and applications.


1 Answers

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

like image 187
Heavy Avatar answered Sep 22 '22 21:09

Heavy