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