Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Logger entering() and exiting() methods

Tags:

java

logging

I just started to use Java Logger. I tried to use its entering() and exiting() methods with hard coded string for class name and method. They both didn't work for me. Just no log entry for them. But other log statements within that methods were logged properly. My logger level is set to CONFIG. I have tried to set to ALL but still cannot see log entry from them.

I found for each entry, there already has a line with class name and method being logged. It seems these two methods are not necessary. But I am still want to know how to make them work for me.

EDIT:

My code followed: these entering() and exiting() are not create an entry in the log file

//class variables
private final static Logger logger = Logger.getLogger(MyClass.class.getName());
private static FileHandler logFileHandler = null;

//within the main() method
Logger thisLogger = Logger.getLogger("");
logFileHandler =  new FileHandler(logFileNameStr, false);
logFileHandler.setFormatter(new SimpleFormatter());
thisLogger.addHandler(logFileHandler);
thisLogger.setLevel(Level.CONFIG);
logger.log(Level.INFO, "Logfile Directory = " + logFileNameStr);


//within a constructor of MyClass
logger.entering("MyClass", "MyClass()");
....
logger.info(initMsg);
....
logger.exiting(this.getClass().getSimpleName(), "MyClass()");
like image 755
5YrsLaterDBA Avatar asked Apr 16 '14 15:04

5YrsLaterDBA


1 Answers

Entering, exiting, and throwing are logged at level FINER. You'll have to set your logger to FINER or lower and set your FileHandler to FINER or lower.

thisLogger.addHandler(logFileHandler);
thisLogger.setLevel(Level.FINER);
logFileHandler.setLevel(Level.ALL);

As far as style goes, you should try creating a static final for class name because you'll use it as the name of the logger and reference it for entering, exiting, throwing, and log precise tracing:

private static final String CLASS_NAME = MyClass.class.getName();

You always want to use a class literal to fetch the name (as above) because getClass().getName() can return a subclass name which can falsify your tracing.

For method names don't include () in the name, just use the entering/exiting method that matches the number of arguments.

For constructor method names use "<init>" and for static init blocks use "<clinit>" as the method name since that is what would show up in a stacktrace.

like image 80
jmehrens Avatar answered Oct 03 '22 22:10

jmehrens