• Advertisement
Sign in to follow this  

C++ Style Macros in Java?

This topic is 2473 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

In C++ I used to use macros to do my logging:

public void log(string message) {
ofstream out("Log.txt");
out << __FILE__ << __LINE__ << message;
out.flush();
}

Unfortunately, Java does not have the __FILE__ and __LINE__ macros, so how can I rewrite log() in Java?

Share this post


Link to post
Share on other sites
Advertisement
You can get the information you need from StackTraceElement.

You'll have todo something like this to obtain the stack, then unwind out of your logging class to the relavent point in the code.



StackTraceElement [] stack = Thread.currentThread().getStackTrace();

// Or...

StackTraceElement [] stack = new Throwable().getStackTrace();

Share this post


Link to post
Share on other sites

so how can I rewrite log() in Java?


You don't.

Java comes with logging built in.

This is especially important since file and line number aren't relevant in logging, they might merely help a bit if an exception is thrown in which case one has a full stack trace. By requirement, file name == class name.

You'll have todo something like this to obtain the stack, then unwind out of your logging class to the relavent point in the code.[/quote]
Let's not do that unless an actual exception occurs.


Also a very important advice: whenever you think you should "rewrite" something in Java, first use the standard library. It's there already, implemented, tested, standardized. If it's not there, it's part of Apache foundation. If it's not there, then Java is the wrong choice.

Apache serves similar role as Boost project. Many of projects that started there matured into standard library, so it's hard to go wrong with it.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement