0
0
Spring Bootframework~5 mins

Log formatting configuration in Spring Boot

Choose your learning style9 modes available
Introduction

Log formatting configuration helps make log messages clear and easy to read. It organizes information like time, level, and message in a consistent way.

You want to see timestamps in your logs to know when events happened.
You need to include the log level (INFO, ERROR) to quickly spot problems.
You want to add extra details like thread name or class name for debugging.
You want logs to be easy to read by humans or machines.
You want to customize logs for different environments (development vs production).
Syntax
Spring Boot
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level [%thread] %logger{36} - %msg%n

This example shows a common pattern for console logs in Spring Boot.

Use placeholders like %d for date, %level for log level, %thread for thread name, %logger for class, and %msg for the message.

Examples
Shows time, log level, and message in a simple format.
Spring Boot
logging.pattern.console=%d{HH:mm:ss} %-5level - %msg%n
Includes milliseconds, thread name, log level, and logger name truncated to 20 characters.
Spring Boot
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{20} - %msg%n
Example pattern for file logs, similar to console but without thread info.
Spring Boot
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
Sample Program

This Spring Boot app logs two messages with a custom format showing date, level, thread, logger, and message.

Spring Boot
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class LogFormatExampleApplication {

    private static final Logger logger = LoggerFactory.getLogger(LogFormatExampleApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(LogFormatExampleApplication.class, args);
        logger.info("Application started successfully.");
        logger.error("An error occurred.");
    }
}

# application.properties
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level [%thread] %logger{36} - %msg%n
OutputSuccess
Important Notes

Use logging.pattern.console for console log format and logging.pattern.file for file logs.

Make sure your pattern includes %n at the end to add a new line after each log message.

Test your log format by running the app and checking the console or log files.

Summary

Log formatting makes logs easier to read and understand.

Use placeholders like %d, %level, %thread, %logger, and %msg to customize logs.

Configure patterns in application.properties for console and file outputs.