log4j is a Java liberary that is used to track the logs about the project execution activity on the console log. In this blog let’s implement the logs into a spring boot project.
Steps to Add log4j into spring boot Project
- Add maven dependency for log4j.
- Configure logs properties into log4j2.properties
- Create a logs object and add the required information that needs to show on the console.
Required Maven Dependency
Add the below dependency into the pom.xml and save the project or update the maven if required.
<!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
Configure logs properties into log4j2.properties
Go to the project path “src/main/resources”, Create a property file with the name “log4j2.properties” in the resources folder. and add the below configuration code.
log4j2.properties
status = error #The level of internal events of Log4j should be logged to the console. name = PropertiesConfig filters = threshold filter.threshold.type = ThresholdFilter filter.threshold.level = debug appenders = console appender.console.type = Console appender.console.name = STDOUT appender.console.layout.type = PatternLayout appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n rootLogger.level = debug rootLogger.appenderRefs = stdout rootLogger.appenderRef.stdout.ref = STDOUT
Create logs using log4j into the spring boot
Create an object of the “Logger “ class and add the logs using Logger .info(” “), there are other methods available in the Logger class that we can use according to the requirements. like LOGGER.debug(” “) and LOGGER.error(” “).
In the below snippet, you can see the demonstration about the implementation of logs using log4j into main runner class of spring boot.
package com.schoolmgt; import org.apache.logging.log4j.LogManager; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SchoolMgtApplication { public static void main(String[] args) { final org.apache.logging.log4j.Logger LOGGER = LogManager.getLogger(SchoolMgtApplication.class); SpringApplication.run(SchoolMgtApplication.class, args); //System.out.println(userDao.findByUserRole("Student").toString()); LOGGER.info("Info log message"); LOGGER.debug("Debug log message"); LOGGER.error("Error log message"); } }