How to handle Logging in Spring Boot?
We have seen what Spring Boot is and how we can create Simple APIs in Spring Boot. Now we will see logging in Spring boot application.
Why logging is required in our application?
Logging in Spring Boot is defined as a framework that enables developers to trace errors that might occur in the running of the application.
Spring boot uses Apache common logging for all internal logging. Spring Boot’s default configurations provide support for the use of Java Util Logging, Log4j2, and Logback. By using Spring Boot starter dependencies we can use logback for logging. Logback also provides good support for Common Logging, Util Logging, Log4J, and SLF4J.
The Default Spring Boot Log format is as shown in the below image.
Following are the details for the above logs printed in the console.
- Date and time: This gives the system date time for the log.
- Log level: INFO, ERROR, or WARN.
- Process Id: This is the processing ID, which is generated by the service, each time we restart the service, a new process ID will be generated.
- —: This is the separator.
- Thread name: [main] is the thread name which is enclosed within the square brackets [].
- Logger name: This shows the source class name.
- Log message: after the source class name we get the actual log message for our application.
By default ‘INFO’, ‘ERROR’, and ‘WARN’ messages will be printed by default, if we want to print debug logs then we can add the following property in the application yml file.
debug: true
Generating log file
As we can see above logs are printed on the console, if we want to generate the log file then we need to add the following property in our application.yml file
logging.file.name: logfile.log
We will get the log file created in our project as shown.
We can also add a path for our log file as below.
logging.file.name: springlog/tmp/logfile.log
We can also set log levels for our application as below.
logging.level.root = DEBUG
Logs will be printed as below
Printing INFO, DEBUG, ERROR, and WARN messages in log files from code
- We can print required messages in the logfile based on the message type if that message is for information purposes then we will print it as INFO in the log.
- Please note that we need to keep the debug property as true for debug messages.
- To print the log using slf4j we will add the following dependency in our pom.xml file.
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
- Once dependency is added we can use @Slf4j annotation at the class level and use the log object to print the logs as shown in the below controller class