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.EnumMap;
21  import java.util.HashMap;
22  import java.util.List;
23  import java.util.Locale;
24  import java.util.Map;
25  
26  import org.apache.logging.log4j.Level;
27  import org.apache.logging.log4j.core.LogEvent;
28  import org.apache.logging.log4j.core.config.Configuration;
29  import org.apache.logging.log4j.core.config.plugins.Plugin;
30  import org.apache.logging.log4j.core.layout.PatternLayout;
31  
32  /**
33   * Highlight pattern converter. Formats the result of a pattern using a color appropriate for the Level in the LogEvent.
34   * <p>
35   * For example:
36   *
37   * <pre>
38   * %highlight{%d{ ISO8601 } [%t] %-5level: %msg%n%throwable}
39   * </pre>
40   * </p>
41   *
42   * <p>
43   * You can define custom colors for each Level:
44   *
45   * <pre>
46   * %highlight{%d{ ISO8601 } [%t] %-5level: %msg%n%throwable}{FATAL=red, ERROR=red, WARN=yellow, INFO=green, DEBUG=cyan,
47   * TRACE=black}
48   * </pre>
49   * </p>
50   *
51   * <p>
52   * You can use a predefined style:
53   *
54   * <pre>
55   * %highlight{%d{ ISO8601 } [%t] %-5level: %msg%n%throwable}{STYLE=Log4j}
56   * </pre>
57   * The available predefined styles are:
58   * <ul>
59   * <li>{@code Default}</li>
60   * <li>{@code Log4j} - The same as {@code Default}</li>
61   * <li>{@code Logback}</li>
62   * </ul>
63   * </p>
64   *
65   * <p>
66   * You can use whitespace around the comma and equal sign. The names in values MUST come from the
67   * {@linkplain AnsiEscape} enum, case is
68   * normalized to upper-case internally.
69   * </p>
70   */
71  @Plugin(name = "highlight", category = "Converter")
72  @ConverterKeys({ "highlight" })
73  public final class HighlightConverter extends LogEventPatternConverter {
74  
75      private static final EnumMap<Level, String> DEFAULT_STYLES = new EnumMap<Level, String>(Level.class);
76  
77      private static final EnumMap<Level, String> LOGBACK_STYLES = new EnumMap<Level, String>(Level.class);
78  
79      private static final String STYLE_KEY = "STYLE";
80  
81      private static final String STYLE_KEY_DEFAULT = "DEFAULT";
82  
83      private static final String STYLE_KEY_LOGBACK = "LOGBACK";
84  
85      private static final Map<String, EnumMap<Level, String>> STYLES = new HashMap<String, EnumMap<Level, String>>();
86  
87      static {
88          // Default styles:
89          DEFAULT_STYLES.put(Level.FATAL, AnsiEscape.createSequence("BRIGHT", "RED"));
90          DEFAULT_STYLES.put(Level.ERROR, AnsiEscape.createSequence("BRIGHT", "RED"));
91          DEFAULT_STYLES.put(Level.WARN, AnsiEscape.createSequence("YELLOW"));
92          DEFAULT_STYLES.put(Level.INFO, AnsiEscape.createSequence("GREEN"));
93          DEFAULT_STYLES.put(Level.DEBUG, AnsiEscape.createSequence("CYAN"));
94          DEFAULT_STYLES.put(Level.TRACE, AnsiEscape.createSequence("BLACK"));
95          // Logback styles:
96          LOGBACK_STYLES.put(Level.FATAL, AnsiEscape.createSequence("BLINK", "BRIGHT", "RED"));
97          LOGBACK_STYLES.put(Level.ERROR, AnsiEscape.createSequence("BRIGHT", "RED"));
98          LOGBACK_STYLES.put(Level.WARN, AnsiEscape.createSequence("RED"));
99          LOGBACK_STYLES.put(Level.INFO, AnsiEscape.createSequence("BLUE"));
100         LOGBACK_STYLES.put(Level.DEBUG, AnsiEscape.createSequence((String[]) null));
101         LOGBACK_STYLES.put(Level.TRACE, AnsiEscape.createSequence((String[]) null));
102         // Style map:
103         STYLES.put(STYLE_KEY_DEFAULT, DEFAULT_STYLES);
104         STYLES.put(STYLE_KEY_LOGBACK, LOGBACK_STYLES);
105     }
106 
107     /**
108      * Creates a level style map where values are ANSI escape sequences given configuration options in
109      * {@code option[1]}.
110      * <p/>
111      * The format of the option string in {@code option[1]} is:
112      *
113      * <pre>
114      * Level1=Value, Level2=Value, ...
115      * </pre>
116      *
117      * For example:
118      *
119      * <pre>
120      * ERROR=red bold, WARN=yellow bold, INFO=green, ...
121      * </pre>
122      *
123      * You can use whitespace around the comma and equal sign. The names in values MUST come from the
124      * {@linkplain AnsiEscape} enum, case is
125      * normalized to upper-case internally.
126      *
127      * @param options
128      *            The second slot can optionally contain the style map.
129      * @return a new map
130      */
131     private static EnumMap<Level, String> createLevelStyleMap(final String[] options) {
132         if (options.length < 2) {
133             return DEFAULT_STYLES;
134         }
135         final Map<String, String> styles = AnsiEscape.createMap(options[1], new String[] {STYLE_KEY});
136         final EnumMap<Level, String> levelStyles = new EnumMap<Level, String>(DEFAULT_STYLES);
137         for (final Map.Entry<String, String> entry : styles.entrySet()) {
138             final String key = entry.getKey().toUpperCase(Locale.ENGLISH);
139             final String value = entry.getValue();
140             if (STYLE_KEY.equalsIgnoreCase(key)) {
141                 final EnumMap<Level, String> enumMap = STYLES.get(value.toUpperCase(Locale.ENGLISH));
142                 if (enumMap == null) {
143                     LOGGER.error("Unknown level style: " + value + ". Use one of " +
144                         Arrays.toString(STYLES.keySet().toArray()));
145                 } else {
146                     levelStyles.putAll(enumMap);
147                 }
148             } else {
149                 final Level level = Level.valueOf(key);
150                 if (level == null) {
151                     LOGGER.error("Unknown level name: " + key + ". Use one of " +
152                         Arrays.toString(DEFAULT_STYLES.keySet().toArray()));
153                 } else {
154                     levelStyles.put(level, value);
155                 }
156             }
157         }
158         return levelStyles;
159     }
160 
161     /**
162      * Gets an instance of the class.
163      *
164      * @param config The current Configuration.
165      * @param options pattern options, may be null. If first element is "short", only the first line of the
166      *                throwable will be formatted.
167      * @return instance of class.
168      */
169     public static HighlightConverter newInstance(final Configuration config, final String[] options) {
170         if (options.length < 1) {
171             LOGGER.error("Incorrect number of options on style. Expected at least 1, received " + options.length);
172             return null;
173         }
174         if (options[0] == null) {
175             LOGGER.error("No pattern supplied on style");
176             return null;
177         }
178         final PatternParser parser = PatternLayout.createPatternParser(config);
179         final List<PatternFormatter> formatters = parser.parse(options[0]);
180         return new HighlightConverter(formatters, createLevelStyleMap(options));
181     }
182 
183     private final EnumMap<Level, String> levelStyles;
184 
185     private final List<PatternFormatter> patternFormatters;
186 
187     /**
188      * Construct the converter.
189      *
190      * @param patternFormatters
191      *            The PatternFormatters to generate the text to manipulate.
192      */
193     private HighlightConverter(final List<PatternFormatter> patternFormatters, final EnumMap<Level, String> levelStyles) {
194         super("style", "style");
195         this.patternFormatters = patternFormatters;
196         this.levelStyles = levelStyles;
197     }
198 
199     /**
200      * {@inheritDoc}
201      */
202     @Override
203     public void format(final LogEvent event, final StringBuilder toAppendTo) {
204         final StringBuilder buf = new StringBuilder();
205         for (final PatternFormatter formatter : patternFormatters) {
206             formatter.format(event, buf);
207         }
208 
209         if (buf.length() > 0) {
210             toAppendTo.append(levelStyles.get(event.getLevel())).append(buf.toString()).
211                 append(AnsiEscape.getDefaultStyle());
212         }
213     }
214 
215     @Override
216     public boolean handlesThrowable() {
217         for (final PatternFormatter formatter : patternFormatters) {
218             if (formatter .handlesThrowable()) {
219                 return true;
220             }
221         }
222         return false;
223     }
224 }