Can a logback message field be truncated/trimmed t

2019-07-06 04:33发布

问题:

Sometimes see huge log messages and do not always have the ability to (easily) turn of word wrapping.

Is there a way to truncate %message to, say, 80 characters via logback.xml?

回答1:

Have a look at the format modifiers section:

From http://logback.qos.ch/manual/layouts.html#formatModifiers:

Format modifiers

By default the relevant information is output as-is. However, with the aid of format modifiers it is possible to change the minimum and maximum width and the justifications of each data field.

...

Truncation from the end is possible by appending a minus character right after the period. In that case, if the maximum field width is eight and the data item is ten characters long, then the last two characters of the data item are dropped.



回答2:

The Adrian's answer is great if you only need to truncate the message. However in my case I wanted to add "... [truncated]" in case of the really truncated messages.

I used a custom convertors mechanism for this purpose - by performing the following steps:

  1. Define you custom converter:
public class LongMessagesConverter extends ClassicConverter {
    private static final int MAX_FORMATTED_MESSAGE_LENGTH = 25600;
    private static final String TRUNCATION_SUFFIX = "... [truncated]";
    private static final int TRUNCATED_MESSAGE_SIZE =
            TRUNCATION_SUFFIX.length() + MAX_FORMATTED_MESSAGE_LENGTH;

@Override
public String convert(ILoggingEvent event) {
    String formattedMessage = event.getFormattedMessage();
    if (formattedMessage == null || 
                 formattedMessage.length() < MAX_FORMATTED_MESSAGE_LENGTH) {
        return formattedMessage;
    }
    return new StringBuilder(TRUNCATED_MESSAGE_SIZE)
            .append(formattedMessage.substring(0, MAX_FORMATTED_MESSAGE_LENGTH))
            .append(TRUNCATION_SUFFIX)
            .toString();
    }
}
  1. Add to your logback.xml the following definition:
<conversionRule conversionWord="boundedMsg" converterClass="your.package.LongMessagesConverter"/>
  1. Replace %msg token with %boundedMsg in your message format pattern


标签: logback