One of the little touches I added to Able, which came from code originally in BrowserMob, was a nice little JDK logging formatter. It is designed to work with modern IDEs (IntelliJ IDEA being my personal favorite) and their ability to understand shorthand notation for classes.
As I was building BrowserMob, I was getting irritated by long package and class names as well as the fact that my log messages weren’t lined up nicely. For example, I’d get:
INFO 12/29 19:26:28 org.directwebremoting.impl.StartupUtil - Starting: DwrGuiceServlet v126.96.36.199.dev INFO 12/29 19:26:31 com.browsermob.stripes.WelcomeActionBean - Some log message INFO 12/29 19:26:37 com.browsermob.stripes.WelcomeActionBean - Some log message
I tried a simple formatter that truncated the class name, but the result wasn’t very helpful, since the class name (usually the most important part) would get cut off when the package name was too long:
INFO 12/29 19:26:28 org.directwebremotin - Starting: DwrGuiceServlet v188.8.131.52.dev INFO 12/29 19:26:31 com.browsermob.strip - Some log message INFO 12/29 19:26:37 com.browsermob.strip - Some log message
That was when I realized that often the package name wasn’t that useful, especially since they were often very predictable and unique even in a compact state. For example, in the past developers I have worked with would often write “n.s.s.c.StripesFilter” as a short hand for “net.sourceforge.stripes.controller.StripesFilter”. So why not use this for logging too? The result was much easier on the eyes:
INFO 12/29 19:26:28 o.d.i.StartupUtil - Starting: DwrGuiceServlet v184.108.40.206.dev INFO 12/29 19:26:31 c.b.s.WelcomeAction~ - Some log message INFO 12/29 19:26:37 c.b.s.WelcomeAction~ - Some log message
Basically, the packages would get cut down to the first letter of each sub-package. If the class name pushes the whole thing beyond 20 characters, then a tilde is added to indicate the name is longer than could fit.
The nice thing about this is that it works beautifully with modern IDEs. I can copy the text “c.b.s.WelcomeAction” and locate that string in IDEA and it’ll know what I mean:
If you want to use this formatter, you can find the code here in the Able source repository. It could probably get some performance improvements, such as some simple memoization, so feel free to send any tweaks you make my way. Do you have any neat tricks you do with logging? If so, please share in the comments!