How to align log messages using java.util.logging

Can someone post how to achieve alignment in the log messages:

[10:14:31 main package1.Class1 <init> INFO]: initializing data.. [10:14:31 Thread-0 package2.Class2 method1 INFO]: log message 

I know I can use log4j, but I want to know how to achieve this with JUL. I tried using MessageFormat, FieldPosition, but to no avail.

thanks

+3
source share
1 answer

You can create your own java.util.logging.Formatter . To do this, you can expand it as follows:

 import java.util.logging.Formatter; import java.util.logging.LogRecord; public final class MyFormatter extends Formatter { @Override public String format(LogRecord record) { StringBuilder sb = new StringBuilder(); // Build output the way you want sb.append(new Date(record.getMillis())) .append(" \t") .append(record.getThreadID()) .append(" \t") .append(record.getSourceMethodName()) .append(" \t") .append(record.getSourceClassName()) .append(" \t") .append(record.getLevel().getLocalizedName()) .append(": ") .append(formatMessage(record)) .append(System.getProperty("line.separator")); return sb.toString(); } } 

You get the idea.

This is just an example of how you can handle the output and align it with \ t. This is not an ideal solution, because you do not know in advance how long SourceMethodName or SourceClassName or any other output field and only one \ t may be insufficient to fully match them.

The solution can be used as much \ t, if necessary, to cover almost all situations that you can think of.

Thus, the ideal solution is to save all the output data and, in the end, calculate how much \ t you need to use depending on the length of each field.

EDIT:

Instead of \ t, you can use StringBuilder along with String.format() for cleaner and easier to read code:

 sb.append(String.Format("[%1$-10s %2$-10s %3$-10s]: %4", new Data(record.getMillis(), record.getSourceMethodName(), record.getSourceClassName(), formatMessage(record) )); 

Check out this page on how to use String.format() to format a string in tables.

+2
source

All Articles