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  package org.apache.logging.log4j.core.pattern;
18  
19  import java.util.Arrays;
20  import java.util.List;
21  
22  import org.apache.logging.log4j.core.LogEvent;
23  import org.apache.logging.log4j.core.config.Configuration;
24  import org.apache.logging.log4j.core.config.plugins.Plugin;
25  import org.apache.logging.log4j.core.layout.PatternLayout;
26  import org.apache.logging.log4j.core.util.Patterns;
27  
28  /**
29   * Style pattern converter. Adds ANSI color styling to the result of the enclosed pattern.
30   */
31  @Plugin(name = "style", category = PatternConverter.CATEGORY)
32  @ConverterKeys({ "style" })
33  public final class StyleConverter extends LogEventPatternConverter implements AnsiConverter {
34  
35      private final List<PatternFormatter> patternFormatters;
36  
37      private final boolean noAnsi;
38  
39      private final String style;
40  
41      private final String defaultStyle;
42  
43      /**
44       * Constructs the converter.
45       *
46       * @param patternFormatters
47       *            The PatternFormatters to generate the text to manipulate.
48       * @param style
49       *            The style that should encapsulate the pattern.
50       * @param noAnsi
51       *            If true, do not output ANSI escape codes.
52       */
53      private StyleConverter(final List<PatternFormatter> patternFormatters, final String style, final boolean noAnsi) {
54          super("style", "style");
55          this.patternFormatters = patternFormatters;
56          this.style = style;
57          this.defaultStyle = AnsiEscape.getDefaultStyle();
58          this.noAnsi = noAnsi;
59      }
60  
61      /**
62       * Gets an instance of the class.
63       *
64       * @param config
65       *            The current Configuration.
66       * @param options
67       *            pattern options, may be null. If first element is "short", only the first line of the throwable will
68       *            be formatted.
69       * @return instance of class.
70       */
71      public static StyleConverter newInstance(final Configuration config, final String[] options) {
72          if (options.length < 1) {
73              LOGGER.error("Incorrect number of options on style. Expected at least 1, received " + options.length);
74              return null;
75          }
76          if (options[0] == null) {
77              LOGGER.error("No pattern supplied on style");
78              return null;
79          }
80          if (options[1] == null) {
81              LOGGER.error("No style attributes provided");
82              return null;
83          }
84          final PatternParser parser = PatternLayout.createPatternParser(config);
85          final List<PatternFormatter> formatters = parser.parse(options[0]);
86          final String style = AnsiEscape.createSequence(options[1].split(Patterns.COMMA_SEPARATOR));
87          final boolean noConsoleNoAnsi = Arrays.toString(options).contains(PatternParser.NO_CONSOLE_NO_ANSI + "=true");
88          final boolean hideAnsi = noConsoleNoAnsi && System.console() == null;
89          return new StyleConverter(formatters, style, hideAnsi);
90      }
91  
92      /**
93       * {@inheritDoc}
94       */
95      @Override
96      public void format(final LogEvent event, final StringBuilder toAppendTo) {
97          int start = 0;
98          int end = 0;
99          if (!noAnsi) { // use ANSI: set prefix
100             start = toAppendTo.length();
101             toAppendTo.append(style);
102             end = toAppendTo.length();
103         }
104 
105         //noinspection ForLoopReplaceableByForEach
106         for (int i = 0, size = patternFormatters.size(); i <  size; i++) {
107             patternFormatters.get(i).format(event, toAppendTo);
108         }
109 
110         // if we use ANSI we need to add the postfix or erase the unnecessary prefix
111         if (!noAnsi) {
112             if (toAppendTo.length() == end) {
113                 toAppendTo.setLength(start); // erase prefix
114             } else {
115                 toAppendTo.append(defaultStyle); // add postfix
116             }
117         }
118     }
119 
120     @Override
121     public boolean handlesThrowable() {
122         for (final PatternFormatter formatter : patternFormatters) {
123             if (formatter.handlesThrowable()) {
124                 return true;
125             }
126         }
127         return false;
128     }
129 
130     /**
131      * Returns a String suitable for debugging.
132      *
133      * @return a String suitable for debugging.
134      */
135     @Override
136     public String toString() {
137         final StringBuilder sb = new StringBuilder();
138         sb.append(super.toString());
139         sb.append("[style=");
140         sb.append(style);
141         sb.append(", defaultStyle=");
142         sb.append(defaultStyle);
143         sb.append(", patternFormatters=");
144         sb.append(patternFormatters);
145         sb.append(", noAnsi=");
146         sb.append(noAnsi);
147         sb.append(']');
148         return sb.toString();
149     }
150 
151 }