C++ Passing extra values to a function

Started by
2 comments, last by REspawn 16 years, 4 months ago
Hi, im working on a message log and I was wondering how I can pass extra values into it when logging a string? So that if a call the log function like this...

int someValue = 1983;
m_log->log("Hello message log %i", someValue);

that it shows up in the log like this...
Quote:Hello message log 1983
Thanks for any help!
Advertisement
Here is a good article to read on the topic.

One additional resource to look at is boost::format. Using this library, you can separate the "creating a log string" part of that code from the "logging the string" part of it, and then not have to worry about the first half. You can do that with stringstreams too, but it takes up a lot more lines of code.
Based on my logger
class LogBuilder{public:	~LogBuilder()	{		// Write the message                // for example, std::cout << log_message.c_str() << std::endl;	}        template <class T>	LogBuilder & operator<<( const T &t ) 	{		log_message << t; 		return *this;	}private:	std::ostrstream log_message;


class Logger{public:	LogBuilder warning( void ) const {		return LogBuilder( Level.WARNING);	}


Usage:
Logger log; log.warning() << "Hello" << "World" << 1983 << 2.5f << some_variable;


This relies on return value optimization (although that isn't required) and stack object life cycle (should be a non-issue, at least I'm not aware of any, excluding possibly VC6. Boost uses same approach in some classes, so it wouldn't appear to be an issue.

The only thing to look out for is that destructor of LogBuilder cannot throw an exception.
Excellent, thanks guys

This topic is closed to new replies.

Advertisement