开发者

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 mec开发者_高级运维hanism 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...");


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.


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.


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.


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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜