Sign in to follow this  
kevin_06s

C++ Style Macros in Java?

Recommended Posts

kevin_06s    106
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
Angex    884
You can get the information you need from [url="http://download.oracle.com/javase/6/docs/api/index.html?java/lang/StackTraceElement.html"]StackTraceElement[/url].

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.

[code]

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

// Or...

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

[/code]

Share this post


Link to post
Share on other sites
Antheus    2409
[quote name='kevin_06s' timestamp='1305836560' post='4813174']
so how can I rewrite log() in Java?
[/quote]

You don't.

Java comes with [url="http://download.oracle.com/javase/6/docs/api/java/util/logging/package-summary.html"]logging built in[/url].

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.

[quote]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 [url="http://www.apache.org/"]Apache[/url] 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

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