• Post Reply Bookmark Topic Watch Topic
  • New Topic

which API could get Method name and calling line number ?  RSS feed

 
Edward Chen
Ranch Hand
Posts: 798
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to get a simple Logger, like

com.myclass (myMethod:line 11) : message.

Now my problem is , which API could get Method name and calling line number (myMethod:line 11) ?

Log4j is too huge, and always has problem to set up properties file. So I want to implement my own logger, just a little more than "System.out.println".

Any suggestion?

Thanks.
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What about Thread.currentThread.getStackTrace() method.

I do recommend you to read the javadoc about it, becuause it has some platform-dependent issues.

I hope this helps.

 
Edward Chen
Ranch Hand
Posts: 798
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it works, although it is not a perfect solution.

Thanks.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a frequent question but one that does not have a good answer. The reason probably goes back to good software design - a called method should have no dependency or knowledge of the calling routine. I used to work with programs in COBOL that had to know who called them, and if you tried to call them from a new place they didn't work. To prevent that kind of mess, Java doesn't really want you to know about who called you.

In loggers, it's often the logging class's responsibility to give this information. I use a framework that has signatures like:

LogHelper.logDebug( PACKAGE_NAME, CLASS_NAME, METHOD_NAME, message );

With any luck your methods are so short that line numbers are not needed.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!