|
| 1 | +package com.baeldung.logging.log4j2.tests; |
| 2 | + |
| 3 | +import org.apache.logging.log4j.Logger; |
| 4 | +import org.apache.logging.log4j.Marker; |
| 5 | +import org.apache.logging.log4j.MarkerManager; |
| 6 | +import org.apache.logging.log4j.ThreadContext; |
| 7 | +import org.apache.logging.log4j.junit.LoggerContextRule; |
| 8 | +import org.junit.Rule; |
| 9 | +import org.junit.Test; |
| 10 | +import org.junit.runner.RunWith; |
| 11 | +import org.junit.runners.JUnit4; |
| 12 | + |
| 13 | +@RunWith(JUnit4.class) |
| 14 | +public class ConsoleAppenderUsingPatternLayoutWithColorsTest { |
| 15 | + @Rule |
| 16 | + public LoggerContextRule contextRule = |
| 17 | + new LoggerContextRule("log4j2-console-appender_pattern-layout.xml"); |
| 18 | + |
| 19 | + @Test |
| 20 | + public void givenLoggerWithConsoleConfig_shouldLogToConsoleInColors() |
| 21 | + throws Exception { |
| 22 | + Logger logger = contextRule.getLogger(getClass().getSimpleName()); |
| 23 | + logger.trace("This is a colored message at TRACE level."); |
| 24 | + logger.debug("This is a colored message at DEBUG level. " + |
| 25 | + "This is the minimum visible level."); |
| 26 | + logger.info("This is a colored message at INFO level."); |
| 27 | + logger.warn("This is a colored message at WARN level."); |
| 28 | + Exception e = new RuntimeException("This is only a test!"); |
| 29 | + logger.error("This is a colored message at ERROR level.", e); |
| 30 | + logger.fatal("This is a colored message at FATAL level."); |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + public void givenLoggerWithConsoleConfig_shouldFilterByMarker() throws Exception { |
| 35 | + Logger logger = contextRule.getLogger("ConnTrace"); |
| 36 | + Marker appError = MarkerManager.getMarker("APP_ERROR"); |
| 37 | + logger.error(appError, "This marker message at ERROR level should be hidden."); |
| 38 | + Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE"); |
| 39 | + logger.trace(connectionTrace, "This is a marker message at TRACE level."); |
| 40 | + } |
| 41 | + |
| 42 | + @Test |
| 43 | + public void givenLoggerWithConsoleConfig_shouldFilterByThreadContext() throws Exception { |
| 44 | + Logger logger = contextRule.getLogger("UserAudit"); |
| 45 | + ThreadContext.put("userId", "1000"); |
| 46 | + logger.info("This is a log-visible user login. Maybe from an admin account?"); |
| 47 | + ThreadContext.put("userId", "1001"); |
| 48 | + logger.info("This is a log-invisible user login."); |
| 49 | + boolean b = true; |
| 50 | + } |
| 51 | +} |
0 commit comments