Last active
October 10, 2015 12:38
-
-
Save bidulock/3691611 to your computer and use it in GitHub Desktop.
Colourify the level of a log4j message by overriding the PatternLayout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
import org.apache.log4j.Level; | |
import org.apache.log4j.PatternLayout; | |
import org.apache.log4j.helpers.PatternConverter; | |
import org.apache.log4j.helpers.PatternParser; | |
import org.apache.log4j.spi.LoggingEvent; | |
public class ColourPatternLayout extends PatternLayout { | |
private static boolean coloursEnabled = "true".equalsIgnoreCase(System.getenv("LOG_COLOURS")); | |
private static Map<Level, String> lookup = new HashMap<Level, String>(); | |
static { | |
lookup.put(Level.TRACE, "\u001b[0;43mTRACE\u001b[m"); | |
lookup.put(Level.DEBUG, "\u001b[0;90mDEBUG\u001b[m"); | |
lookup.put(Level.INFO, "\u001b[0;36mINFO \u001b[m"); | |
lookup.put(Level.WARN, "\u001b[0;33mWARN \u001b[m"); | |
lookup.put(Level.ERROR, "\u001b[0;31mERROR\u001b[m"); | |
lookup.put(Level.FATAL, "\u001b[1;31mFATAL\u001b[m"); | |
} | |
@Override protected PatternParser createPatternParser(String pattern) { | |
return new PatternParser(pattern) { | |
@Override protected void finalizeConverter(char c) { | |
if (coloursEnabled && c == 'p') { | |
addConverter(new PatternConverter() { | |
protected String convert(LoggingEvent event) { | |
return lookup.get(event.getLevel()); | |
} | |
}); | |
} else { | |
super.finalizeConverter(c); | |
} | |
} | |
}; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment