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