Posted By:
Nadeem_Awad
Posted On:
Monday, February 5, 2007 09:17 AM
Hi, I've been using Log4j, and I found it a little troublesome to declare an instance variable everywhere and pass the class name to it; like this: public class UsesLogger { Logger logger = Logger.getLogger(this.class); ... public void log() { logger.debug( "bla bla" ); } } So I thought I could create a wrapper class to encapsulate the logger. For instance: public class MyLogger { public static void log(Class clazz, String message) { Logger logger = Logger.getLogger(clazz); logger.debug(message); } } But I also didn't li
More>>
Hi,
I've been using Log4j, and I found it a little troublesome to declare an instance variable everywhere and pass the class name to it; like this:
public
class
UsesLogger {
Logger logger = Logger.getLogger(this.class);
...
public
void log() {
logger.debug(
"bla bla"
);
}
}
So I thought I could create a wrapper class to encapsulate the logger. For instance:
public
class
MyLogger {
public
static
void log(Class clazz, String message) {
Logger logger = Logger.getLogger(clazz);
logger.debug(message);
}
}
But I also didn't like passing the class object every time I want to log a message. So the following came to my mind:
public
class
MyLogger {
private
static
Exception ex =
new
Exception();
public
static
void log(String message) {
ex.fillInStackTrace();
StackTraceElement[] ste = ex.getStackTrace();
Logger logger = Logger.getLogger(ste[1].getClassName());
//I even can add the method name to the message using ste[1].getMethodName()
logger.debug(message);
}
}
So the other classes do the following:
public
class
UsesLogger() {
public
void aMethod() {
MyLogger.log(
"inside aMethod"
);
}
}
My question is, is this approach efficient? especially that the ex.fillInStackTrace() method is synchronized, so it might be a bit costly.
Any ideas?
<<Less