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          final StringBuilder buf = new StringBuilder();
98          for (final PatternFormatter formatter : patternFormatters) {
99              formatter.format(event, buf);
100         }
101 
102         if (buf.length() > 0) {
103             if (noAnsi) {
104                 // faster to test and do this than setting style and defaultStyle to empty strings.
105                 toAppendTo.append(buf.toString());
106             } else {
107                 toAppendTo.append(style).append(buf.toString()).append(defaultStyle);
108             }
109         }
110     }
111 
112     @Override
113     public boolean handlesThrowable() {
114         for (final PatternFormatter formatter : patternFormatters) {
115             if (formatter.handlesThrowable()) {
116                 return true;
117             }
118         }
119         return false;
120     }
121 
122     /**
123      * Returns a String suitable for debugging.
124      *
125      * @return a String suitable for debugging.
126      */
127     @Override
128     public String toString() {
129         final StringBuilder sb = new StringBuilder();
130         sb.append(super.toString());
131         sb.append("[style=");
132         sb.append(style);
133         sb.append(", defaultStyle=");
134         sb.append(defaultStyle);
135         sb.append(", patternFormatters=");
136         sb.append(patternFormatters);
137         sb.append(", noAnsi=");
138         sb.append(noAnsi);
139         sb.append(']');
140         return sb.toString();
141     }
142 
143 }