We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,272 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Fast method name access for logging

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

2
Contributors
2
Replies
3 Hours
Discussion Span
8 Months Ago
Last Updated
3
Views
Question
Answered
sampsont
Newbie Poster
7 posts since Mar 2009
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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!

JasonHippy
Practically a Posting Shark
862 posts since Jan 2009
Reputation Points: 615
Solved Threads: 146
Skill Endorsements: 5

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.

sampsont
Newbie Poster
7 posts since Mar 2009
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 8 Months Ago by JasonHippy

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0684 seconds using 2.77MB