Format Modifiers

Format modifiers allow you to specify the exact number of characters used to represent a field. Format modifiers come after the percent sign and before the conversion specifier.

The following table lists format modifiers and their affects:

Format Modifier
Justified
Min Width
Max Width
Comments
%20
Right
20
None
Field is left padded with spaces to be a minimum of 20 characters long.
%-10
Left
10
None
Field is right padded with spaces to be a minimum of 10 characters long.
%.15
NA
None
15
Field is truncated if it is longer than 15 characters.
%-20.30
Left
20
30
Combines both justification and truncation. In this case, right padding up to 20 spaces and truncating if necessary after 30.
%5.5
Right
5
5
In this example, we are specifying a field with a fixed width of 5. Fixed width fields can be very useful when continuous string data.

As an example, consider the following log entry.

2012-05-09 10:50:14 A Test14Start - Initializing...

There are two things to note about this log entry. First, there are 5 spaces after the 'A'. Second the string 'Test14Start' actually contains three pieces of information an ID, a Position, and an Action.

The above log entry can be parsed with the conversion pattern:

%d %-5c %4.4s{ID}%2.2s{POS}%5.5s{ACTION} - %m%n

Using this conversion pattern, the log entry will be parsed as:

Format Modifier
Value
Comments
%d
2012-05-09 10:50:14
The date.
%-5c
A
The extra 5 spaces are ignored. Note that if our conversion pattern had contained two spaces between this specifier and the next, we would have had a parsing error.
%4.4s{ID}
Test
The next field is a fixed 11 characters. The first four will be the ID.
%2.2s{POS}
14
...the next two will be the Position.
%5.5s{ACTION}
Start
...and the final 5 will be the Action. Note that these three fields must always be exactly 11 characters long.
%m
Initializing...
The message.

You can find out more about format modifiers online. The Apache documentation is a particularly good place to start.

< >