Search code examples
javaformatterjava.util.logging

Using simple class name in java logging formatter


I have a SimpleFormatter for logging in my application with the string
"%1$tF %1$tT %4$-7s %2$s %5$s%6$s%n"

I would like to use the simple class name rather than the canonical name. Is there a format option I can use with the 2$ field? Or does this require writing a new Handler?

For example, rather than
2019-02-06 07:09:09 INFO simplex.tools.SIMPLEXScheduler main Start

I'd like to see
2019-02-06 07:09:09 INFO SIMPLEXScheduler main Start


Solution

  • Is there a format option I can use with the 2$ field?

    The SimpleFormatter only supports the functionality in the java.util.Formatter. Currently there is no way to format class name as simple class name.

    Or does this require writing a new Handler?

    One option is to write a new java.util.logging.Formatter. There are some hacks that you can do by just installing a java.util.logging.Filter to change the class name but you should avoid doing that. Use logp instead as suggested by P.J.Meisch

    Disclaimer: I'm a content developer for com.sun.mail.util.logging package included with the JavaMail project.

    If you have access to JavaMail you can use the com.sun.mail.util.logging.CompactFormatter which will only print the simple class name. The trade off is that it will print compact stack traces for exceptions. Arguments 1 through 6 are the same order as the SimpleFormatter so the same pattern can be used.

    If you don't want to include JavaMail then you can use the com.sun.mail:logging-mailhandler artifact instead.