View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  
18  package org.apache.logging.log4j.core.pattern;
19  
20  import java.util.List;
21  
22  import org.apache.logging.log4j.core.LogEvent;
23  import org.apache.logging.log4j.core.appender.AbstractAppender;
24  import org.apache.logging.log4j.core.config.Configuration;
25  import org.apache.logging.log4j.core.config.plugins.Plugin;
26  import org.apache.logging.log4j.core.layout.PatternLayout;
27  import org.apache.logging.log4j.util.PerformanceSensitive;
28  
29  /**
30   * Max length pattern converter. Limit contained text to a maximum length.
31   * On invalid length the default value 100 is used (and an error message is logged).
32   * If max length is greater than 20, an abbreviated text will get ellipsis ("...") appended.
33   * Example usage (for email subject):
34   * {@code "%maxLen{[AppName, ${hostName}, ${web:contextPath}] %p: %c{1} - %m%notEmpty{ =>%ex{short}}}{160}"}
35   *
36   * @author Thies Wellpott
37   */
38  @Plugin(name = "maxLength", category = PatternConverter.CATEGORY)
39  @ConverterKeys({"maxLength", "maxLen"})
40  @PerformanceSensitive("allocation")
41  public final class MaxLengthConverter extends LogEventPatternConverter {
42  
43      /**
44       * Gets an instance of the class.
45       *
46       * @param config  The current Configuration.
47       * @param options pattern options, an array of two elements: pattern, max length (defaults to 100 on invalid value).
48       * @return instance of class.
49       */
50      public static MaxLengthConverter newInstance(final Configuration config, final String[] options) {
51          if (options.length != 2) {
52              LOGGER.error("Incorrect number of options on maxLength: expected 2 received {}: {}", options.length,
53                  options);
54              return null;
55          }
56          if (options[0] == null) {
57              LOGGER.error("No pattern supplied on maxLength");
58              return null;
59          }
60          if (options[1] == null) {
61              LOGGER.error("No length supplied on maxLength");
62              return null;
63          }
64          final PatternParser parser = PatternLayout.createPatternParser(config);
65          final List<PatternFormatter> formatters = parser.parse(options[0]);
66          return new MaxLengthConverter(formatters, AbstractAppender.parseInt(options[1], 100));
67      }
68  
69  
70      private final List<PatternFormatter> formatters;
71      private final int maxLength;
72  
73      /**
74       * Construct the converter.
75       *
76       * @param formatters The PatternFormatters to generate the text to manipulate.
77       * @param maxLength  The max. length of the resulting string. Ellipsis ("...") is appended on shorted string, if greater than 20.
78       */
79      private MaxLengthConverter(final List<PatternFormatter> formatters, final int maxLength) {
80          super("MaxLength", "maxLength");
81          this.maxLength = maxLength;
82          this.formatters = formatters;
83          LOGGER.trace("new MaxLengthConverter with {}", maxLength);
84      }
85  
86  
87      @Override
88      public void format(final LogEvent event, final StringBuilder toAppendTo) {
89          final int initialLength = toAppendTo.length();
90          for (int i = 0; i < formatters.size(); i++) {
91              final PatternFormatter formatter = formatters.get(i);
92              formatter.format(event, toAppendTo);
93              if (toAppendTo.length() > initialLength + maxLength) {        // stop early
94                  break;
95              }
96          }
97          if (toAppendTo.length() > initialLength + maxLength) {
98              toAppendTo.setLength(initialLength + maxLength);
99              if (maxLength > 20) {        // only append ellipses if length is not very short
100                 toAppendTo.append("...");
101             }
102         }
103     }
104 }