Printing method class and line number
1 posts in topic
Flat View  Flat View

Posted By:   anjali_naveen
Posted On:   Wednesday, September 7, 2005 07:26 AM

I have a wrapper around a log4J logger. Using pattern layout i print to console and a file. The problem im facing is in printing the method name, class name and line number. Since my l7dlog or log method calls are within the wrapper, the line number class and method name reflect the method inside the wrapper and not from where the log might have actually been logged. How do i work around this problem

Re: Printing method class and line number

Posted By:   Christopher_Koenigsberg  
Posted On:   Saturday, September 10, 2005 04:27 PM

I follow a convention where in each class I get a 'private static transient Logger = Logger.getLogger(MyClassName.class);'.

Then in each method, I declare 'final String myLogName = this.getClass().getName() + ".myMethodName"; '. Or if the method is static, it has to be 'final String myLogName = MyClassName.class.getName() + ".myMethodName";'.

And finally, when I actually want to log something inside the method, I do 'logger.debug(myLogName + " blah blah blah.");'.

What comes out in the log is a very long line, but it includes the logger's name, which is actually the name of the class (fully qualified with package prefix) that got the logger, plus it also contains the name of the method, with its fully qualified class too.

There are cases where having both of these on the log line provides interesting information, e.g. when the same methods from common parent classes are invoked in multiple different subclasses, etc.

For getting a line number, I think you may have to do an ugly hack like throwing an Exception and catching it yourself and giving it to the logger as the 2nd arg so the stack trace gets logged.

('logger.debug(myLogName + " info on my current stack trace and line number:", e);' where "e" is the Exception that you threw and caught yourself)
About | Sitemap | Contact