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 with 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' that follows the date.  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 4 spaces are ignored.  If our conversion pattern had contained two spaces between this specifier and the next, we would read into the next field and parsing would fail.
%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.  Taken together, these three fields must always be exactly 11 characters long.
%m
Initializing...
The message.  This could be any length and may span multiple lines.

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


< >