I trying to incorporate a simple error logging into my existing app, at the moment it reports errors just using cout so I was hoping to keep a similar interface using the << operator. However I want it to log the line and function the error occurred, but I don’t want to have to type __LINE__, __FUNCTION__ every time I need to log. Does anyone know a trick I can use to allow the __LINE__ macro to be used inside another function, reporting the calling line instead? Hope that makes sense.
class myLogClass { uint8_t level; public: bool operator<<( const char * input ); }; bool myLogClass::operator<<( const char * input ) { logItInSQL( input ); return true; }
Instead of this every time
myLogClass << 'Line No: ' << __LINE__ << ' Function: ' << __FUNCTION__ << ' Error: ' << 'This is my error to be logged';
I would like to just be able to do:
myLogClass << 'This is my error to be logged'; bool myLogClass::operator<<( const char * input ) { logItInSQL( ' Line No: __LINE__' ); logItInSQL( ' Function: __FUNCTION__' ); logItInSQL( ' Error: ' + input ); return true; }
With your
operator <<chaining will not work since it returns abool.It is customary to define stream insertion as follows:
Do this:
Additionally, you can wrap the macro in a
do-whileloop:Then you can happily write: