Tag Archives: log4j2 using environment variable

Java configure Log4j2 in your Project

  1. Log4j2 and SLF4j Binding Dependencies
    To make Log4j2 work with SLF4J, we need to include the following 3 dependencies.
    log4j-slf4j-impl.jar – Log4j 2 SLF4J binding. It allows applications coded to the SLF4J API to use Log4j2 as the implementation.
    log4j-api.jar – provides the adapter components required for implementers to create a logging implementation.
    log4j-core.jar – core Log4j Implementation classes.
    The Maven and Gradle dependencies can be copied as below.
    pom.xml

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.15.0</version> </dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.15.0</version>
</dependency> <dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.15.0</version>
</dependency>

  1. Create File log4j2.xml in your Project resources folder
    Example with file rolling and using system variables and made for use under wildfly server:

<?xml version=”1.0″ encoding=”UTF-8″?>
<Configuration status=”${env:LOG_LEVEL}”>
<Appenders>
<RollingFile name=”LogToFile” fileName=”${env:JBOSS_HOME}/standalone/log/xxx.log” filePattern=”${env:JBOSS_HOME}/standalone/log/xxx.log-%d{yyyy-MM-dd}”> <PatternLayout>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} – %msg%n </pattern> </PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval=”1″ modulate=”true” />
<OnStartupTriggeringPolicy />
</Policies> <!– Max 10 files will be created everyday –>
<DefaultRolloverStrategy max=”20″>
<Delete basePath=”${env:JBOSS_HOME}/standalone/log/” maxDepth=”10″>
<!– Delete all files older than 30 days –>
<IfLastModified age=”30d” />
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
</Appenders>
<Loggers>
<!– avoid duplicated logs with additivity=false –>
<Logger name=”xxx-be” level=”${env:LOG_LEVEL}” additivity=”false”> <AppenderRef ref=”LogToFile”/>
</Logger>
<Root level=”${env:LOG_LEVEL}”>
<AppenderRef ref=”LogToFile”/>
</Root>
</Loggers>
</Configuration>

  1. log4j2.xml
  2. Using Logger in Code
    import org.apache.logging.log4j.Logger;
    Logger logger = LogManager.getLogger(“xxx-be”);
    logger.info(“startet”);

I needed whole day to make it work I hope this will help developers.