To print custom logs in console of your IDE is very easy with LoggerFactory inbuilt package of SLF4J (Simple Logging Facade for Java). In this article I will explain you, how to use this package to print the custom logs in the console in spring boot.
Follow few simple project in your spring boot application to print the custom logs in console:
Step 1: First you need to add the following line in your application.properties or application.yml file of your spring boot project. This blog line is very important to add in your project because when you run your spring boot project then it will be loading lots of logs in your console and all logs will not visible in the console.
logging.file.name=application.log
Restart your spring boot project after adding the above line in your spring boot project. It will create an application.log file in your project root folder in which your all console logs will print.
Step 2: All the following lines in your project (Depends on Maven or Gradle)
If your spring boot project is based on Maven, add the following line in pom.xml file.
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.16</version>
</dependency>
If your spring boot project is based on Gradle, add the following line in build.gradle file.
// https://mvnrepository.com/artifact/org.slf4j/slf4j-api
implementation group: 'org.slf4j', name: 'slf4j-api', version: '2.0.16'
Note: If you want to check the latest version of the slf4j package click on the given link https://mvnrepository.com/artifact/org.slf4j/slf4j-api
Step 3: Add the following code similarly in your spring boot project where you want to add the logs in your project.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class YoureCustomClassServices {
private static final Logger logger =
LoggerFactory.getLogger(YoureCustomClassServices.class);
public void yourCustomeMethod() {
logger.info("***** CUSTOM LOG MESSAGE *****");
}
}
or,
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class YoureCustomClassServices {
public void yourCustomeMethod() {
LoggerFactory.getLogger(YoureCustomClassServices.class).info("***** CUSTOM LOG MESSAGE *****");
}
}
No comments:
Post a Comment