In Creating Loggers DRY-ly by Dr. Heinz M. Kabutz, he mentioned typical copy-paste and (forgot to) modify error when creating a static logger variable, which cause logging is incorrect (wrong class name) and thereby confusing. He suggested 2 ways, first is to leave the static logger undefined, and initialize it in an initializer block. The other is to create a LoggerFactory that uses the method call stack (Throwable.getStackTrace()[1]) to determine from where it is being called. It saves works, and does not have few limitations as the first way. Sounds good, if you do not mind it is actually a trick, and a little bit overhead.
IMHO, if you have a good IDE, and you do not want to use the above ways, you may manipulate your IDE auto-completion template/shortcut, if possible. In Eclipse, Window --> Preferences --> Java --> Editor --> Templates, create a new template with the below name qlogger, and patterns:
private static final Logger logger = Logger.getLogger(${primary_type_name}.class.getName());
${cursor}
Now, everytime for a new class that need to create logger variable, just type qlogger, then Ctrl+Space. The ${primary_type_name} will be replaced by the current file name. Of course, it won't work for other classes that exists in the same file that is not public, and it does not look like an advanced professional tip, but it works. :)

0 comments:
Post a Comment