Karthik
Karthik

Reputation: 3

Alternatives to macro substitution in java

I have a log statement in which I always use this.getClass().getSimpleName()as the 1st parameter. I would like to put this in some sort of macro constant and use that in all my log statements. But I learned that Java has no such simple mechanism unlike say C++.

What is the best way to achieve this sort of functionality in Java?

My example log statements (from Android) is as follows..

Log.v(this.getClass().getSimpleName(),"Starting LocIden service...");

Upvotes: 0

Views: 3138

Answers (4)

Augusto
Augusto

Reputation: 29997

Karthik, most logging tools allow you to specify the format of the output and one of the parameters is the class name, which uses the method Mark mentioned (stack inspection)

For example, in log4j the parameter is %C to reference a class name.

Upvotes: 1

OrangeDog
OrangeDog

Reputation: 38797

Use a proper logging framework (e.g. slf4j). Each class that logs has its own logger, so there's no need to pass the class name to the log method call.

Logger logger = LoggerFactory.getLogger(this.getClass());

logger.debug("Starting service");
//...
logger.debug("Service started");

Upvotes: -1

Falmarri
Falmarri

Reputation: 48587

Another approach is to follow what android suggests for its logging functionality.

Log.v(TAG, "Message");

where TAG is a private static final string in your class.

Upvotes: -1

Mark Byers
Mark Byers

Reputation: 838906

Java doesn't have macros but you can make your code much shorter:

Log.v(this, "Starting LocIden service...");

And in the Log class:

public void v(Object object, String s)
{
    _v(object.getClass().getSimpleName(), s);
}

Another approach could be to inspect the call stack.

Upvotes: 5

Related Questions