public class MyTest {
public static void main(String args[]) {
new MyTest().doit();
}
public void doit() {
System.out.println(new Exception().getStackTrace()[0].getMethodName());
}
}
| Real Gagnon from Quebec, Canada
+ LookingForJavaOrPowerBuilderSnippets? VisitReal'sHow-to
|
I have a Logger class that logs application events and exceptions, and I currently have to use a static string for each method name to pass to it. Now I can eliminate those and the maintenance that goes with them.
I know that I can replace my home-built Logger class with the new 1.4 standard, but...
I looked at the API for the Logger class in 1.4 and it does log the method name, but as far as I can tell it's just a String that I have to provide to it. I doesn't seem to "know" the method name automatically.
if you are trying to record every time a method is invoked, why not invoke the logging api from the class that is being invoked. therefore you always know the name.
you could say:
if (logging)
myLogger(**log something**)
obviously this is at a very high level! but it does avoid the mess that you will be creating by invoking calls to the runtime - dont bother with a quick fix. head in book all day breeds good results
That's essentially what I do, only the logging boolean is a static property of the Logger class so I can turn it on and off with a menu item ("turn on debug logging".
Specifically:
[ignore]
There are two different styles of logging methods, to meet the needs of different communities of users.
First, there are methods that take an explicit source class name and source method name. These methods are intended for developers who want to be able to quickly locate the source of any given logging message. An example of this style is:
Second, there are a set of methods that do not take explicit source class or source method names. These are intended for developers who want easy-to-use logging and do not require detailed source information.
void warning(String msg);
For this second set of methods, the Logging framework will make a "best effort" to determine which class and method called into the logging framework and will add this information into the LogRecord. However, it is important to realize that this automatically inferred information may only be approximate. The latest generation of virtual machines perform extensive optimizations when JITing and may entirely remove stack frames, making it impossible to reliably locate the calling class and method.
[/ignore]
Hope this helps
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.