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  
28  /**
29   * Max length pattern converter. Limit contained text to a maximum length.
30   * On invalid length the default value 100 is used (and an error message is logged).
31   * If max length is greater than 20, an abbreviated text will get ellipsis ("...") appended.
32   * Example usage (for email subject):
33   * {@code "%maxLen{[AppName, ${hostName}, ${web:contextPath}] %p: %c{1} - %m%notEmpty{ =>%ex{short}}}{160}"}
34   *
35   * @author Thies Wellpott
36   */
37  @Plugin(name = "maxLength", category = PatternConverter.CATEGORY)
38  @ConverterKeys({"maxLength", "maxLen"})
39  public final class MaxLengthConverter extends LogEventPatternConverter {
40  
41      /**
42       * Gets an instance of the class.
43       *
44       * @param config  The current Configuration.
45       * @param options pattern options, an array of two elements: pattern, max length (defaults to 100 on invalid value).
46       * @return instance of class.
47       */
48      public static MaxLengthConverter newInstance(final Configuration config, final String[] options) {
49          if (options.length != 2) {
50              LOGGER.error("Incorrect number of options on maxLength: expected 2 received {}: {}", options.length,
51                  options);
52              return null;
53          }
54          if (options[0] == null) {
55              LOGGER.error("No pattern supplied on maxLength");
56              return null;
57          }
58          if (options[1] == null) {
59              LOGGER.error("No length supplied on maxLength");
60              return null;
61          }
62          final PatternParser parser = PatternLayout.createPatternParser(config);
63          final List<PatternFormatter> formatters = parser.parse(options[0]);
64          return new MaxLengthConverter(formatters, AbstractAppender.parseInt(options[1], 100));
65      }
66  
67  
68      private final List<PatternFormatter> formatters;
69      private final int maxLength;
70  
71      /**
72       * Construct the converter.
73       *
74       * @param formatters The PatternFormatters to generate the text to manipulate.
75       * @param maxLength  The max. length of the resulting string. Ellipsis ("...") is appended on shorted string, if greater than 20.
76       */
77      private MaxLengthConverter(final List<PatternFormatter> formatters, final int maxLength) {
78          super("MaxLength", "maxLength");
79          this.maxLength = maxLength;
80          this.formatters = formatters;
81          LOGGER.trace("new MaxLengthConverter with {}", maxLength);
82      }
83  
84  
85      @Override
86      public void format(final LogEvent event, final StringBuilder toAppendTo) {
87          final StringBuilder buf = new StringBuilder();
88          for (final PatternFormatter formatter : formatters) {
89              formatter.format(event, buf);
90              if (buf.length() > maxLength) {        // stop early
91                  break;
92              }
93          }
94          if (buf.length() > maxLength) {
95              buf.setLength(maxLength);
96              if (maxLength > 20) {        // only append ellipses if length is not very short
97                  buf.append("...");
98              }
99          }
100         toAppendTo.append(buf);
101     }
102 
103 }