Search code examples
c++ooploggingwrapperostream

Logger system - using levels c++


How can I use a function from (Wrap ostream in class and templatize << operator)

I want to use SEVERITY levels for the logger and each level can take any number of msg/ elements

This class accept any number for elements in the object but I need it also for each function in the class ex:

ClassName ClassObject(&std::cout)
ClassObject.info() << "test msg" << 5 << 10 << endl;

this is my class

class logger {

private:
    ostream * str;

public:

    logger( ostream* str_v) : str(str_v) {}

    template <class T>
    logger& operator<<(T&& x) {
        *str << std::forward<T>(x);
        return *this;
    }

    logger& operator<<(ostream& (*manip)(ostream&)) {
        *str << manip;
        return *this;
    }

    void info(){
        cout <<"hello world"<<endl;
    }
};

int main(){

   logger l(&std::cout);
    l << 5 << std::string(" test")<<endl;
   //I want to use info like that
   l.info() << "print anything" << 5 << endl;

    return 0;

}

Solution

  • For a very simple solution, let info() write to *str and return a reference to *this:

    logger& info()
    {
        *str << "info - ";
        return *this;
    }
    

    Then is can be used as you wish:

    l.info() << "print anything" << 5 << endl;
    

    The above should print

    info - print anything 5