Sign in to follow this  
REspawn

C++ Passing extra values to a function

Recommended Posts

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!

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this