Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trimming the Log4J Message

Tags:

java

log4j

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.

like image 495
Matt N Avatar asked Jan 06 '09 16:01

Matt N


1 Answers

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.

like image 173
James Van Huis Avatar answered Sep 29 '22 16:09

James Van Huis