I have an appender that I only want the first X characters (for this example, we'll say 5) of the message to display.
I am using a PatternLayout but I can't get the message to truncate the message correctly.
For example, if my log message is
The quick brown fox
I just want to see :
The q
When I use this in the Pattern
%.5m
I get
n fox
since those are the last 5 characters.
I've looked the PattenLayout javadoc, but could not find anything. I know this is a little strange to not want to see the entire message, but for this specific appender it makes sense. I do log the entire message in a different appender. I would like to avoid writing a custom class if possible.
Truncation is done from the beginning of a message by default (differs from the printf in C, which does it from the end).
The proper pattern should be:
%.-5m
EDIT:
I just tried this, and log4j does not like that pattern. However, the supplied pattern will work fine in LOGBack, if you can make the switch over. If you cannot switch your logging provider, you could make a one-off modification to log4j. The interesting bit of code appears on lines 75-76 of org.apache.log4j.helpers.PatternConverter:
if(len > max)
sbuf.append(s.substring(len-max));
This should read:
if(len > max)
sbuf.append(s.substring(0,max));
You can simply make the modification and recompile the jar for your use, or you can subclass PatternConverter to perform the proper truncation. This will also require a new version of PatternLayout, which contains the createPatternParser method, which you will need to override in your subclass to instantiate your new version of PatternConverter.
As a side note, be aware of the licensing ramifications of modifying open source code in your specific project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With