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, TRACE=black}
047     * </pre>
048     * </p>
049     * 
050     * <p>
051     * You can use a predefined style:
052     * 
053     * <pre>
054     * %highlight{%d{ ISO8601 } [%t] %-5level: %msg%n%throwable}{STYLE=Log4J}
055     * </pre>
056     * The available predefined styles are:
057     * <ul>
058     * <li>{@code Default}</li>
059     * <li>{@code Log4J} - The same as {@code Default}</li>
060     * <li>{@code Logback}</li>
061     * </ul>
062     * </p>
063     * 
064     * <p>
065     * You can use whitespace around the comma and equal sign. The names in values MUST come from the {@linkplain AnsiEscape} enum, case is
066     * normalized to upper-case internally.
067     * </p>
068     */
069    @Plugin(name = "highlight", type = "Converter")
070    @ConverterKeys({ "highlight" })
071    public final class HighlightConverter extends LogEventPatternConverter {
072    
073        private static final String STYLE_KEY_DEFAULT = "DEFAULT";
074    
075        private static final String STYLE_KEY_LOGBACK = "LOGBACK";
076    
077        private static final String STYLE_KEY = "STYLE";
078    
079        private static final EnumMap<Level, String> DEFAULT_STYLES = new EnumMap<Level, String>(Level.class);
080    
081        private static final EnumMap<Level, String> LOGBACK_STYLES = new EnumMap<Level, String>(Level.class);
082    
083        private static final Map<String, EnumMap<Level, String>> STYLES = new HashMap<String, EnumMap<Level, String>>();
084    
085        static {
086            // Default styles:
087            DEFAULT_STYLES.put(Level.FATAL, AnsiEscape.createSequence(new String[] { "BRIGHT", "RED" }));
088            DEFAULT_STYLES.put(Level.ERROR, AnsiEscape.createSequence(new String[] { "BRIGHT", "RED" }));
089            DEFAULT_STYLES.put(Level.WARN, AnsiEscape.createSequence(new String[] { "YELLOW" }));
090            DEFAULT_STYLES.put(Level.INFO, AnsiEscape.createSequence(new String[] { "GREEN" }));
091            DEFAULT_STYLES.put(Level.DEBUG, AnsiEscape.createSequence(new String[] { "CYAN" }));
092            DEFAULT_STYLES.put(Level.TRACE, AnsiEscape.createSequence(new String[] { "BLACK" }));
093            // Logback styles:
094            LOGBACK_STYLES.put(Level.FATAL, AnsiEscape.createSequence(new String[] { "BLINK", "BRIGHT", "RED" }));
095            LOGBACK_STYLES.put(Level.ERROR, AnsiEscape.createSequence(new String[] { "BRIGHT", "RED" }));
096            LOGBACK_STYLES.put(Level.WARN, AnsiEscape.createSequence(new String[] { "RED" }));
097            LOGBACK_STYLES.put(Level.INFO, AnsiEscape.createSequence(new String[] { "BLUE" }));
098            LOGBACK_STYLES.put(Level.DEBUG, AnsiEscape.createSequence(null));
099            LOGBACK_STYLES.put(Level.TRACE, AnsiEscape.createSequence(null));
100            // Style map:
101            STYLES.put(STYLE_KEY_DEFAULT, DEFAULT_STYLES);
102            STYLES.put(STYLE_KEY_LOGBACK, LOGBACK_STYLES);
103        }
104    
105        /**
106         * Creates a level style map where values are ANSI escape sequences given configuration options in {@code option[1]}.
107         * <p/>
108         * The format of the option string in {@code option[1]} is:
109         * 
110         * <pre>
111         * Level1=Value, Level2=Value, ...
112         * </pre>
113         * 
114         * For example:
115         * 
116         * <pre>
117         * ERROR=red bold, WARN=yellow bold, INFO=green, ...
118         * </pre>
119         * 
120         * You can use whitespace around the comma and equal sign. The names in values MUST come from the {@linkplain AnsiEscape} enum, case is
121         * normalized to upper-case internally.
122         * 
123         * @param options
124         *            The second slot can optionally contain the style map.
125         * @return a new map
126         */
127        private static EnumMap<Level, String> createLevelStyleMap(final String[] options) {
128            if (options.length < 2) {
129                return DEFAULT_STYLES;
130            }
131            Map<String, String> styles = AnsiEscape.createMap(options[1], new String[] { STYLE_KEY });
132            EnumMap<Level, String> levelStyles = new EnumMap<Level, String>(DEFAULT_STYLES);
133            for (Map.Entry<String, String> entry : styles.entrySet()) {
134                final String key = entry.getKey().toUpperCase(Locale.ENGLISH);
135                final String value = entry.getValue();
136                if (STYLE_KEY.equalsIgnoreCase(key)) {
137                    final EnumMap<Level, String> enumMap = STYLES.get(value.toUpperCase(Locale.ENGLISH));
138                    if (enumMap == null) {
139                        LOGGER.error("Unkown level style: " + value + ". Use one of " + Arrays.toString(STYLES.keySet().toArray()));
140                    } else {
141                        levelStyles.putAll(enumMap);
142                    }
143                } else {
144                    final Level level = Level.valueOf(key);
145                    if (level == null) {
146                        LOGGER.error("Unkown level name: " + key + ". Use one of " + Arrays.toString(DEFAULT_STYLES.keySet().toArray()));
147                    } else {
148                        levelStyles.put(level, value);
149                    }
150                }
151            }
152            return levelStyles;
153        }
154    
155        /**
156         * Gets an instance of the class.
157         * 
158         * @param config
159         *            The current Configuration.
160         * @param options
161         *            pattern options, may be null. If first element is "short", only the first line of the throwable will be formatted.
162         * @return instance of class.
163         */
164        public static HighlightConverter newInstance(Configuration config, final String[] options) {
165            if (options.length < 1) {
166                LOGGER.error("Incorrect number of options on style. Expected at least 1, received " + options.length);
167                return null;
168            }
169            if (options[0] == null) {
170                LOGGER.error("No pattern supplied on style");
171                return null;
172            }
173            PatternParser parser = PatternLayout.createPatternParser(config);
174            List<PatternFormatter> formatters = parser.parse(options[0]);
175            return new HighlightConverter(formatters, createLevelStyleMap(options));
176        }
177    
178        private final List<PatternFormatter> formatters;
179    
180        private final EnumMap<Level, String> levelStyles;
181    
182        /**
183         * Construct the converter.
184         * 
185         * @param formatters
186         *            The PatternFormatters to generate the text to manipulate.
187         */
188        private HighlightConverter(List<PatternFormatter> formatters, EnumMap<Level, String> levelStyles) {
189            super("style", "style");
190            this.formatters = formatters;
191            this.levelStyles = levelStyles;
192        }
193    
194        /**
195         * {@inheritDoc}
196         */
197        @Override
198        public void format(final LogEvent event, final StringBuilder toAppendTo) {
199            StringBuilder buf = new StringBuilder();
200            for (PatternFormatter formatter : formatters) {
201                formatter.format(event, buf);
202            }
203    
204            if (buf.length() > 0) {
205                toAppendTo.append(levelStyles.get(event.getLevel())).append(buf.toString()).append(AnsiEscape.getDefaultStyle());
206            }
207        }
208    }