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  import org.apache.logging.log4j.core.util.Patterns;
26  
27  /**
28   * Style pattern converter. Adds ANSI color styling to the result of the enclosed pattern.
29   */
30  @Plugin(name = "style", category = PatternConverter.CATEGORY)
31  @ConverterKeys({ "style" })
32  public final class StyleConverter extends LogEventPatternConverter implements AnsiConverter {
33  
34      /**
35       * Gets an instance of the class.
36       *
37       * @param config
38       *            The current Configuration.
39       * @param options
40       *            pattern options, may be null. If first element is "short", only the first line of the throwable will
41       *            be formatted.
42       * @return instance of class.
43       */
44      public static StyleConverter newInstance(final Configuration config, final String[] options) {
45          if (options.length < 1) {
46              LOGGER.error("Incorrect number of options on style. Expected at least 1, received " + options.length);
47              return null;
48          }
49          if (options[0] == null) {
50              LOGGER.error("No pattern supplied on style");
51              return null;
52          }
53          if (options[1] == null) {
54              LOGGER.error("No style attributes provided");
55              return null;
56          }
57          final PatternParser parser = PatternLayout.createPatternParser(config);
58          final List<PatternFormatter> formatters = parser.parse(options[0]);
59          final String style = AnsiEscape.createSequence(options[1].split(Patterns.COMMA_SEPARATOR));
60          final boolean noConsoleNoAnsi = options.length > 2
61                  && (PatternParser.NO_CONSOLE_NO_ANSI + "=true").equals(options[2]);
62          final boolean hideAnsi = noConsoleNoAnsi && System.console() == null;
63          return new StyleConverter(formatters, style, hideAnsi);
64      }
65  
66      private final List<PatternFormatter> patternFormatters;
67  
68      private final boolean noAnsi;
69  
70      private final String style;
71  
72      private final String defaultStyle;
73  
74      /**
75       * Constructs the converter.
76       *
77       * @param patternFormatters
78       *            The PatternFormatters to generate the text to manipulate.
79       * @param style
80       *            The style that should encapsulate the pattern.
81       * @param noAnsi
82       *            If true, do not output ANSI escape codes.
83       */
84      private StyleConverter(final List<PatternFormatter> patternFormatters, final String style, final boolean noAnsi) {
85          super("style", "style");
86          this.patternFormatters = patternFormatters;
87          this.style = style;
88          this.defaultStyle = AnsiEscape.getDefaultStyle();
89          this.noAnsi = noAnsi;
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 }