001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements. See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache license, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License. You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the license for the specific language governing permissions and
015     * limitations under the license.
016     */
017    package org.apache.logging.log4j.core.pattern;
018    
019    import java.util.Arrays;
020    import java.util.EnumMap;
021    import java.util.HashMap;
022    import java.util.List;
023    import java.util.Locale;
024    import java.util.Map;
025    
026    import org.apache.logging.log4j.Level;
027    import org.apache.logging.log4j.core.LogEvent;
028    import org.apache.logging.log4j.core.config.Configuration;
029    import org.apache.logging.log4j.core.config.plugins.Plugin;
030    import org.apache.logging.log4j.core.layout.PatternLayout;
031    
032    /**
033     * Highlight pattern converter. Formats the result of a pattern using a color appropriate for the Level in the LogEvent.
034     * <p>
035     * For example:
036     *
037     * <pre>
038     * %highlight{%d{ ISO8601 } [%t] %-5level: %msg%n%throwable}
039     * </pre>
040     * </p>
041     *
042     * <p>
043     * You can define custom colors for each Level:
044     *
045     * <pre>
046     * %highlight{%d{ ISO8601 } [%t] %-5level: %msg%n%throwable}{FATAL=red, ERROR=red, WARN=yellow, INFO=green, DEBUG=cyan,
047     * TRACE=black}
048     * </pre>
049     * </p>
050     *
051     * <p>
052     * You can use a predefined style:
053     *
054     * <pre>
055     * %highlight{%d{ ISO8601 } [%t] %-5level: %msg%n%throwable}{STYLE=Log4j}
056     * </pre>
057     * The available predefined styles are:
058     * <ul>
059     * <li>{@code Default}</li>
060     * <li>{@code Log4j} - The same as {@code Default}</li>
061     * <li>{@code Logback}</li>
062     * </ul>
063     * </p>
064     *
065     * <p>
066     * You can use whitespace around the comma and equal sign. The names in values MUST come from the
067     * {@linkplain AnsiEscape} enum, case is
068     * normalized to upper-case internally.
069     * </p>
070     */
071    @Plugin(name = "highlight", category = "Converter")
072    @ConverterKeys({ "highlight" })
073    public final class HighlightConverter extends LogEventPatternConverter {
074    
075        private static final String STYLE_KEY_DEFAULT = "DEFAULT";
076    
077        private static final String STYLE_KEY_LOGBACK = "LOGBACK";
078    
079        private static final String STYLE_KEY = "STYLE";
080    
081        private static final EnumMap<Level, String> DEFAULT_STYLES = new EnumMap<Level, String>(Level.class);
082    
083        private static final EnumMap<Level, String> LOGBACK_STYLES = new EnumMap<Level, String>(Level.class);
084    
085        private static final Map<String, EnumMap<Level, String>> STYLES = new HashMap<String, EnumMap<Level, String>>();
086    
087        private final List<PatternFormatter> formatters;
088    
089        private final EnumMap<Level, String> levelStyles;
090    
091        static {
092            // Default styles:
093            DEFAULT_STYLES.put(Level.FATAL, AnsiEscape.createSequence("BRIGHT", "RED"));
094            DEFAULT_STYLES.put(Level.ERROR, AnsiEscape.createSequence("BRIGHT", "RED"));
095            DEFAULT_STYLES.put(Level.WARN, AnsiEscape.createSequence("YELLOW"));
096            DEFAULT_STYLES.put(Level.INFO, AnsiEscape.createSequence("GREEN"));
097            DEFAULT_STYLES.put(Level.DEBUG, AnsiEscape.createSequence("CYAN"));
098            DEFAULT_STYLES.put(Level.TRACE, AnsiEscape.createSequence("BLACK"));
099            // Logback styles:
100            LOGBACK_STYLES.put(Level.FATAL, AnsiEscape.createSequence("BLINK", "BRIGHT", "RED"));
101            LOGBACK_STYLES.put(Level.ERROR, AnsiEscape.createSequence("BRIGHT", "RED"));
102            LOGBACK_STYLES.put(Level.WARN, AnsiEscape.createSequence("RED"));
103            LOGBACK_STYLES.put(Level.INFO, AnsiEscape.createSequence("BLUE"));
104            LOGBACK_STYLES.put(Level.DEBUG, AnsiEscape.createSequence((String[]) null));
105            LOGBACK_STYLES.put(Level.TRACE, AnsiEscape.createSequence((String[]) null));
106            // Style map:
107            STYLES.put(STYLE_KEY_DEFAULT, DEFAULT_STYLES);
108            STYLES.put(STYLE_KEY_LOGBACK, LOGBACK_STYLES);
109        }
110    
111        /**
112         * Construct the converter.
113         *
114         * @param formatters
115         *            The PatternFormatters to generate the text to manipulate.
116         */
117        private HighlightConverter(final List<PatternFormatter> formatters, final EnumMap<Level, String> levelStyles) {
118            super("style", "style");
119            this.formatters = formatters;
120            this.levelStyles = levelStyles;
121        }
122    
123        /**
124         * Creates a level style map where values are ANSI escape sequences given configuration options in
125         * {@code option[1]}.
126         * <p/>
127         * The format of the option string in {@code option[1]} is:
128         *
129         * <pre>
130         * Level1=Value, Level2=Value, ...
131         * </pre>
132         *
133         * For example:
134         *
135         * <pre>
136         * ERROR=red bold, WARN=yellow bold, INFO=green, ...
137         * </pre>
138         *
139         * You can use whitespace around the comma and equal sign. The names in values MUST come from the
140         * {@linkplain AnsiEscape} enum, case is
141         * normalized to upper-case internally.
142         *
143         * @param options
144         *            The second slot can optionally contain the style map.
145         * @return a new map
146         */
147        private static EnumMap<Level, String> createLevelStyleMap(final String[] options) {
148            if (options.length < 2) {
149                return DEFAULT_STYLES;
150            }
151            final Map<String, String> styles = AnsiEscape.createMap(options[1], new String[] {STYLE_KEY});
152            final EnumMap<Level, String> levelStyles = new EnumMap<Level, String>(DEFAULT_STYLES);
153            for (final Map.Entry<String, String> entry : styles.entrySet()) {
154                final String key = entry.getKey().toUpperCase(Locale.ENGLISH);
155                final String value = entry.getValue();
156                if (STYLE_KEY.equalsIgnoreCase(key)) {
157                    final EnumMap<Level, String> enumMap = STYLES.get(value.toUpperCase(Locale.ENGLISH));
158                    if (enumMap == null) {
159                        LOGGER.error("Unknown level style: " + value + ". Use one of " +
160                            Arrays.toString(STYLES.keySet().toArray()));
161                    } else {
162                        levelStyles.putAll(enumMap);
163                    }
164                } else {
165                    final Level level = Level.valueOf(key);
166                    if (level == null) {
167                        LOGGER.error("Unknown level name: " + key + ". Use one of " +
168                            Arrays.toString(DEFAULT_STYLES.keySet().toArray()));
169                    } else {
170                        levelStyles.put(level, value);
171                    }
172                }
173            }
174            return levelStyles;
175        }
176    
177        /**
178         * Gets an instance of the class.
179         *
180         * @param config The current Configuration.
181         * @param options pattern options, may be null. If first element is "short", only the first line of the
182         *                throwable will be formatted.
183         * @return instance of class.
184         */
185        public static HighlightConverter newInstance(final Configuration config, final String[] options) {
186            if (options.length < 1) {
187                LOGGER.error("Incorrect number of options on style. Expected at least 1, received " + options.length);
188                return null;
189            }
190            if (options[0] == null) {
191                LOGGER.error("No pattern supplied on style");
192                return null;
193            }
194            final PatternParser parser = PatternLayout.createPatternParser(config);
195            final List<PatternFormatter> formatters = parser.parse(options[0]);
196            return new HighlightConverter(formatters, createLevelStyleMap(options));
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 : formatters) {
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    }