Contents
Import Maven dependency
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.12.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.12.1</version> </dependency>
Configuration File
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="INFO"> <Properties> <Property name="logPath">./</Property> <Property name="rollingFileName">log4j2_demo_log</Property> <Property name="logPath">/var/log/log4j2</Property> </Properties> <Appenders> <Console name="console" target="SYSTEM_OUT"> <PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" /> </Console> <RollingFile name="rollingFile" fileName="${logPath}/${rollingFileName}.log" filePattern="${logPath}/${rollingFileName}_%d{yyyy-MM-dd}.log"> <PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" /> <Policies> <!-- Causes a rollover if the log file is older than the current JVM's start time --> <OnStartupTriggeringPolicy /> <!-- Causes a rollover once the date/time pattern no longer applies to the active file --> <TimeBasedTriggeringPolicy interval="1" modulate="true" /> </Policies> </RollingFile> </Appenders> <Loggers> <Root level="TRACE" additivity="false"> <AppenderRef ref="console" /> <AppenderRef ref="rollingFile" /> </Root> </Loggers> </Configuration>
Code
package log4j2demo; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Log4j2Demo { private static final Logger logger = LogManager.getLogger(Log4j2Demo.class); public static void main(String[] args) { logger.trace("trace message"); logger.info("info message"); logger.debug("debug message"); logger.error("error message"); } }
Console Output
[TRACE] 2019-10-03 14:31:42,481 Log4j2Demo.main() - trace message [INFO ] 2019-10-03 14:31:42,484 Log4j2Demo.main() - info message [DEBUG] 2019-10-03 14:31:42,484 Log4j2Demo.main() - debug message [ERROR] 2019-10-03 14:31:42,485 Log4j2Demo.main() - error message