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 */ 017package org.apache.logging.log4j.core.pattern; 018 019import java.util.Arrays; 020import java.util.HashMap; 021import java.util.List; 022import java.util.Locale; 023import java.util.Map; 024 025import org.apache.logging.log4j.Level; 026import org.apache.logging.log4j.core.LogEvent; 027import org.apache.logging.log4j.core.config.Configuration; 028import org.apache.logging.log4j.core.config.plugins.Plugin; 029import org.apache.logging.log4j.core.layout.PatternLayout; 030import org.apache.logging.log4j.util.PerformanceSensitive; 031import org.apache.logging.log4j.util.Strings; 032 033/** 034 * Highlight pattern converter. Formats the result of a pattern using a color appropriate for the Level in the LogEvent. 035 * <p> 036 * For example: 037 * </p> 038 * 039 * <pre> 040 * %highlight{%d{ ISO8601 } [%t] %-5level: %msg%n%throwable} 041 * </pre> 042 * <p> 043 * You can define custom colors for each Level: 044 * </p> 045 * 046 * <pre> 047 * %highlight{%d{ ISO8601 } [%t] %-5level: %msg%n%throwable}{FATAL=red, ERROR=red, WARN=yellow, INFO=green, DEBUG=cyan, 048 * TRACE=black} 049 * </pre> 050 * <p> 051 * You can use a predefined style: 052 * </p> 053 * 054 * <pre> 055 * %highlight{%d{ ISO8601 } [%t] %-5level: %msg%n%throwable}{STYLE=DEFAULT} 056 * </pre> 057 * <p> 058 * The available predefined styles are: 059 * </p> 060 * <ul> 061 * <li>{@code Default}</li> 062 * <li>{@code Log4j} - The same as {@code Default}</li> 063 * <li>{@code Logback}</li> 064 * </ul> 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 normalized to upper-case internally. 068 * </p> 069 * 070 * <p> 071 * To disable ANSI output unconditionally, specify an additional option <code>disableAnsi=true</code>, or to 072 * disable ANSI output if no console is detected, specify option <code>noConsoleNoAnsi=true</code> e.g.. 073 * </p> 074 * <pre> 075 * %highlight{%d{ ISO8601 } [%t] %-5level: %msg%n%throwable}{STYLE=DEFAULT, noConsoleNoAnsi=true} 076 * </pre> 077 */ 078@Plugin(name = "highlight", category = PatternConverter.CATEGORY) 079@ConverterKeys({ "highlight" }) 080@PerformanceSensitive("allocation") 081public final class HighlightConverter extends LogEventPatternConverter implements AnsiConverter { 082 083 private static final Map<Level, String> DEFAULT_STYLES = new HashMap<>(); 084 085 private static final Map<Level, String> LOGBACK_STYLES = new HashMap<>(); 086 087 private static final String STYLE_KEY = "STYLE"; 088 089 private static final String STYLE_KEY_DEFAULT = "DEFAULT"; 090 091 private static final String STYLE_KEY_LOGBACK = "LOGBACK"; 092 093 private static final Map<String, Map<Level, String>> STYLES = new HashMap<>(); 094 095 static { 096 // Default styles: 097 DEFAULT_STYLES.put(Level.FATAL, AnsiEscape.createSequence("BRIGHT", "RED")); 098 DEFAULT_STYLES.put(Level.ERROR, AnsiEscape.createSequence("BRIGHT", "RED")); 099 DEFAULT_STYLES.put(Level.WARN, AnsiEscape.createSequence("YELLOW")); 100 DEFAULT_STYLES.put(Level.INFO, AnsiEscape.createSequence("GREEN")); 101 DEFAULT_STYLES.put(Level.DEBUG, AnsiEscape.createSequence("CYAN")); 102 DEFAULT_STYLES.put(Level.TRACE, AnsiEscape.createSequence("BLACK")); 103 // Logback styles: 104 LOGBACK_STYLES.put(Level.FATAL, AnsiEscape.createSequence("BLINK", "BRIGHT", "RED")); 105 LOGBACK_STYLES.put(Level.ERROR, AnsiEscape.createSequence("BRIGHT", "RED")); 106 LOGBACK_STYLES.put(Level.WARN, AnsiEscape.createSequence("RED")); 107 LOGBACK_STYLES.put(Level.INFO, AnsiEscape.createSequence("BLUE")); 108 LOGBACK_STYLES.put(Level.DEBUG, AnsiEscape.createSequence((String[]) null)); 109 LOGBACK_STYLES.put(Level.TRACE, AnsiEscape.createSequence((String[]) null)); 110 // Style map: 111 STYLES.put(STYLE_KEY_DEFAULT, DEFAULT_STYLES); 112 STYLES.put(STYLE_KEY_LOGBACK, LOGBACK_STYLES); 113 } 114 115 /** 116 * Creates a level style map where values are ANSI escape sequences given configuration options in {@code option[1]} 117 * . 118 * <p> 119 * The format of the option string in {@code option[1]} is: 120 * </p> 121 * 122 * <pre> 123 * Level1=Value, Level2=Value, ... 124 * </pre> 125 * 126 * <p> 127 * For example: 128 * </p> 129 * 130 * <pre> 131 * ERROR=red bold, WARN=yellow bold, INFO=green, ... 132 * </pre> 133 * 134 * <p> 135 * You can use whitespace around the comma and equal sign. The names in values MUST come from the 136 * {@linkplain AnsiEscape} enum, case is normalized to upper-case internally. 137 * </p> 138 * 139 * @param options 140 * The second slot can optionally contain the style map. 141 * @return a new map 142 */ 143 private static Map<Level, String> createLevelStyleMap(final String[] options) { 144 if (options.length < 2) { 145 return DEFAULT_STYLES; 146 } 147 // Feels like a hack. Should String[] options change to a Map<String,String>? 148 final String string = options[1] 149 .replaceAll(PatternParser.DISABLE_ANSI + "=(true|false)", Strings.EMPTY) 150 .replaceAll(PatternParser.NO_CONSOLE_NO_ANSI + "=(true|false)", Strings.EMPTY); 151 // 152 final Map<String, String> styles = AnsiEscape.createMap(string, new String[] {STYLE_KEY}); 153 final Map<Level, String> levelStyles = new HashMap<>(DEFAULT_STYLES); 154 for (final Map.Entry<String, String> entry : styles.entrySet()) { 155 final String key = entry.getKey().toUpperCase(Locale.ENGLISH); 156 final String value = entry.getValue(); 157 if (STYLE_KEY.equalsIgnoreCase(key)) { 158 final Map<Level, String> enumMap = STYLES.get(value.toUpperCase(Locale.ENGLISH)); 159 if (enumMap == null) { 160 LOGGER.error("Unknown level style: " + value + ". Use one of " + 161 Arrays.toString(STYLES.keySet().toArray())); 162 } else { 163 levelStyles.putAll(enumMap); 164 } 165 } else { 166 final Level level = Level.toLevel(key, null); 167 if (level == null) { 168 LOGGER.error("Unknown level name: {}; use one of {}", key, Arrays.toString(Level.values())); 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 final boolean disableAnsi = Arrays.toString(options).contains(PatternParser.DISABLE_ANSI + "=true"); 197 final boolean noConsoleNoAnsi = Arrays.toString(options).contains(PatternParser.NO_CONSOLE_NO_ANSI + "=true"); 198 final boolean hideAnsi = disableAnsi || (noConsoleNoAnsi && System.console() == null); 199 return new HighlightConverter(formatters, createLevelStyleMap(options), hideAnsi); 200 } 201 202 private final Map<Level, String> levelStyles; 203 204 private final List<PatternFormatter> patternFormatters; 205 206 private final boolean noAnsi; 207 208 private final String defaultStyle; 209 210 /** 211 * Construct the converter. 212 * 213 * @param patternFormatters 214 * The PatternFormatters to generate the text to manipulate. 215 * @param noAnsi 216 * If true, do not output ANSI escape codes. 217 */ 218 private HighlightConverter(final List<PatternFormatter> patternFormatters, final Map<Level, String> levelStyles, final boolean noAnsi) { 219 super("style", "style"); 220 this.patternFormatters = patternFormatters; 221 this.levelStyles = levelStyles; 222 this.defaultStyle = AnsiEscape.getDefaultStyle(); 223 this.noAnsi = noAnsi; 224 } 225 226 /** 227 * {@inheritDoc} 228 */ 229 @Override 230 public void format(final LogEvent event, final StringBuilder toAppendTo) { 231 int start = 0; 232 int end = 0; 233 if (!noAnsi) { // use ANSI: set prefix 234 start = toAppendTo.length(); 235 toAppendTo.append(levelStyles.get(event.getLevel())); 236 end = toAppendTo.length(); 237 } 238 239 //noinspection ForLoopReplaceableByForEach 240 for (int i = 0, size = patternFormatters.size(); i < size; i++) { 241 patternFormatters.get(i).format(event, toAppendTo); 242 } 243 244 // if we use ANSI we need to add the postfix or erase the unnecessary prefix 245 final boolean empty = toAppendTo.length() == end; 246 if (!noAnsi) { 247 if (empty) { 248 toAppendTo.setLength(start); // erase prefix 249 } else { 250 toAppendTo.append(defaultStyle); // add postfix 251 } 252 } 253 } 254 255 String getLevelStyle(Level level) { 256 return levelStyles.get(level); 257 } 258 259 @Override 260 public boolean handlesThrowable() { 261 for (final PatternFormatter formatter : patternFormatters) { 262 if (formatter .handlesThrowable()) { 263 return true; 264 } 265 } 266 return false; 267 } 268 269}