I like to have the name of the current method for logging purposes. For example:

string Commands::test(StringTokenizer& tokens)
{
    static string src("Commands::test");
    ...
    _log.debug("message", src);
}

I'm worried that creating 'src' might cause a performance hit. I made the string static thinking it would only be constructed once, the first time it is used and from then on, it would be available.

Am I correct in thinking that 'static string src' will only be constructed once and then be available instantly from then on? Is there a better way to force 'src' to be created once and remain in memory somewhere and be persistently available?

PS: I would like for 'src' to be a local variable because it's easy to initialize it there. Trying to handle it as a class property or somewhere else seems to get messy.

I would very much appreciate any suggestions!
Todd

Recommended Answers

All 2 Replies

If you are using a version of Visual Studio, you could just pass the __FUNCTION__ macro into your logging function.
e.g.
_log.debug("message", __FUNCTION__);

The function macro will pass the name of the current function as a string.
see: http://msdn.microsoft.com/en-us/library/b0084kay%28v=vs.80%29.aspx

I think the __FUNCTION__ macro is also defined in gcc, so it should work for gcc, g++, mingw and cygwin too.

But if you're using another compiler, you might have to consult its documentation to see if there are any similar macros defined!

I'm using g++. __FUNCTION__ does indeed work! Very nice but it only prints the method name, (as you would expect). I was hoping to print 'class::func'. Different classes can often have the same method names. It's important for me to log the class name as well.

I did some more experimenting and I think I convinced myself that a local static variable is only initialized once, the first time the method is called.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.