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 == null) {
80              return null;
81          }
82          if (options.length < 2) {
83              LOGGER.error("Incorrect number of options on style. Expected at least 1, received " + options.length);
84              return null;
85          }
86          if (options[0] == null) {
87              LOGGER.error("No pattern supplied for style converter");
88              return null;
89          }
90          if (options[1] == null) {
91              LOGGER.error("No style attributes supplied for style converter");
92              return null;
93          }
94          final PatternParser parser = PatternLayout.createPatternParser(config);
95          final List<PatternFormatter> formatters = parser.parse(options[0]);
96          final String style = AnsiEscape.createSequence(options[1].split(Patterns.COMMA_SEPARATOR));
97          final boolean disableAnsi = Arrays.toString(options).contains(PatternParser.DISABLE_ANSI + "=true");
98          final boolean noConsoleNoAnsi = Arrays.toString(options).contains(PatternParser.NO_CONSOLE_NO_ANSI + "=true");
99          final boolean hideAnsi = disableAnsi || (noConsoleNoAnsi && System.console() == null);
100         return new StyleConverter(formatters, style, hideAnsi);
101     }
102 
103     /**
104      * {@inheritDoc}
105      */
106     @Override
107     public void format(final LogEvent event, final StringBuilder toAppendTo) {
108         int start = 0;
109         int end = 0;
110         if (!noAnsi) { // use ANSI: set prefix
111             start = toAppendTo.length();
112             toAppendTo.append(style);
113             end = toAppendTo.length();
114         }
115 
116         //noinspection ForLoopReplaceableByForEach
117         for (int i = 0, size = patternFormatters.size(); i <  size; i++) {
118             patternFormatters.get(i).format(event, toAppendTo);
119         }
120 
121         // if we use ANSI we need to add the postfix or erase the unnecessary prefix
122         if (!noAnsi) {
123             if (toAppendTo.length() == end) {
124                 toAppendTo.setLength(start); // erase prefix
125             } else {
126                 toAppendTo.append(defaultStyle); // add postfix
127             }
128         }
129     }
130 
131     @Override
132     public boolean handlesThrowable() {
133         for (final PatternFormatter formatter : patternFormatters) {
134             if (formatter.handlesThrowable()) {
135                 return true;
136             }
137         }
138         return false;
139     }
140 
141     /**
142      * Returns a String suitable for debugging.
143      *
144      * @return a String suitable for debugging.
145      */
146     @Override
147     public String toString() {
148         final StringBuilder sb = new StringBuilder();
149         sb.append(super.toString());
150         sb.append("[style=");
151         sb.append(style);
152         sb.append(", defaultStyle=");
153         sb.append(defaultStyle);
154         sb.append(", patternFormatters=");
155         sb.append(patternFormatters);
156         sb.append(", noAnsi=");
157         sb.append(noAnsi);
158         sb.append(']');
159         return sb.toString();
160     }
161 
162 }