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.HashMap;
021    import java.util.List;
022    import java.util.Locale;
023    import java.util.Map;
024    
025    import org.apache.logging.log4j.Level;
026    import org.apache.logging.log4j.core.LogEvent;
027    import org.apache.logging.log4j.core.config.Configuration;
028    import org.apache.logging.log4j.core.config.plugins.Plugin;
029    import org.apache.logging.log4j.core.layout.PatternLayout;
030    import org.apache.logging.log4j.util.Strings;
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 implements AnsiConverter {
074    
075        private static final Map<Level, String> DEFAULT_STYLES = new HashMap<Level, String>();
076    
077        private static final Map<Level, String> LOGBACK_STYLES = new HashMap<Level, String>();
078    
079        private static final String STYLE_KEY = "STYLE";
080    
081        private static final String STYLE_KEY_DEFAULT = "DEFAULT";
082    
083        private static final String STYLE_KEY_LOGBACK = "LOGBACK";
084    
085        private static final Map<String, Map<Level, String>> STYLES = new HashMap<String, Map<Level, String>>();
086    
087        static {
088            // Default styles:
089            DEFAULT_STYLES.put(Level.FATAL, AnsiEscape.createSequence("BRIGHT", "RED"));
090            DEFAULT_STYLES.put(Level.ERROR, AnsiEscape.createSequence("BRIGHT", "RED"));
091            DEFAULT_STYLES.put(Level.WARN, AnsiEscape.createSequence("YELLOW"));
092            DEFAULT_STYLES.put(Level.INFO, AnsiEscape.createSequence("GREEN"));
093            DEFAULT_STYLES.put(Level.DEBUG, AnsiEscape.createSequence("CYAN"));
094            DEFAULT_STYLES.put(Level.TRACE, AnsiEscape.createSequence("BLACK"));
095            // Logback styles:
096            LOGBACK_STYLES.put(Level.FATAL, AnsiEscape.createSequence("BLINK", "BRIGHT", "RED"));
097            LOGBACK_STYLES.put(Level.ERROR, AnsiEscape.createSequence("BRIGHT", "RED"));
098            LOGBACK_STYLES.put(Level.WARN, AnsiEscape.createSequence("RED"));
099            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 Map<Level, String> createLevelStyleMap(final String[] options) {
132            if (options.length < 2) {
133                return DEFAULT_STYLES;
134            }
135            // Feels like a hack. Should String[] options change to a Map<String,String>?
136            String string = options[1].replaceAll(PatternParser.NO_CONSOLE_NO_ANSI + "=(true|false)", Strings.EMPTY);
137            //
138            final Map<String, String> styles = AnsiEscape.createMap(string, new String[] {STYLE_KEY});
139            final Map<Level, String> levelStyles = new HashMap<Level, String>(DEFAULT_STYLES);
140            for (final Map.Entry<String, String> entry : styles.entrySet()) {
141                final String key = entry.getKey().toUpperCase(Locale.ENGLISH);
142                final String value = entry.getValue();
143                if (STYLE_KEY.equalsIgnoreCase(key)) {
144                    final Map<Level, String> enumMap = STYLES.get(value.toUpperCase(Locale.ENGLISH));
145                    if (enumMap == null) {
146                        LOGGER.error("Unknown level style: " + value + ". Use one of " +
147                            Arrays.toString(STYLES.keySet().toArray()));
148                    } else {
149                        levelStyles.putAll(enumMap);
150                    }
151                } else {
152                    final Level level = Level.toLevel(key);
153                    if (level == null) {
154                        LOGGER.error("Unknown level name: " + key + ". Use one of " +
155                            Arrays.toString(DEFAULT_STYLES.keySet().toArray()));
156                    } else {
157                        levelStyles.put(level, value);
158                    }
159                }
160            }
161            return levelStyles;
162        }
163    
164        /**
165         * Gets an instance of the class.
166         *
167         * @param config The current Configuration.
168         * @param options pattern options, may be null. If first element is "short", only the first line of the
169         *                throwable will be formatted.
170         * @return instance of class.
171         */
172        public static HighlightConverter newInstance(final Configuration config, final String[] options) {
173            if (options.length < 1) {
174                LOGGER.error("Incorrect number of options on style. Expected at least 1, received " + options.length);
175                return null;
176            }
177            if (options[0] == null) {
178                LOGGER.error("No pattern supplied on style");
179                return null;
180            }
181            final PatternParser parser = PatternLayout.createPatternParser(config);
182            final List<PatternFormatter> formatters = parser.parse(options[0]);
183            return new HighlightConverter(formatters, createLevelStyleMap(options));
184        }
185    
186        private final Map<Level, String> levelStyles;
187    
188        private final List<PatternFormatter> patternFormatters;
189    
190        /**
191         * Construct the converter.
192         *
193         * @param patternFormatters
194         *            The PatternFormatters to generate the text to manipulate.
195         */
196        private HighlightConverter(final List<PatternFormatter> patternFormatters, final Map<Level, String> levelStyles) {
197            super("style", "style");
198            this.patternFormatters = patternFormatters;
199            this.levelStyles = levelStyles;
200        }
201    
202        /**
203         * {@inheritDoc}
204         */
205        @Override
206        public void format(final LogEvent event, final StringBuilder toAppendTo) {
207            final StringBuilder buf = new StringBuilder();
208            for (final PatternFormatter formatter : patternFormatters) {
209                formatter.format(event, buf);
210            }
211    
212            if (buf.length() > 0) {
213                toAppendTo.append(levelStyles.get(event.getLevel())).append(buf.toString()).
214                    append(AnsiEscape.getDefaultStyle());
215            }
216        }
217    
218        @Override
219        public boolean handlesThrowable() {
220            for (final PatternFormatter formatter : patternFormatters) {
221                if (formatter .handlesThrowable()) {
222                    return true;
223                }
224            }
225            return false;
226        }
227    }