How to Log to File in Spring Boot: Simple Setup Guide
logging.file.name or logging.file.path property in application.properties or application.yml. This tells Spring Boot to write logs to the specified file or directory automatically without extra code.Syntax
Spring Boot uses properties to control logging output. The main properties are:
logging.file.name: Specifies the exact file path for the log file.logging.file.path: Specifies a directory where Spring Boot creates a default log file namedspring.log.logging.level.*: Controls the log level (e.g., INFO, DEBUG) for packages or classes.
These properties go into application.properties or application.yml in your project.
# application.properties
logging.file.name=logs/myapp.log
logging.level.root=INFOExample
This example shows how to configure Spring Boot to log to a file named myapp.log inside a logs folder. The log level is set to INFO.
When you run the Spring Boot application, logs will be saved to logs/myapp.log automatically.
package com.example.loggingdemo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.CommandLineRunner; @SpringBootApplication public class LoggingDemoApplication implements CommandLineRunner { private static final Logger logger = LoggerFactory.getLogger(LoggingDemoApplication.class); public static void main(String[] args) { SpringApplication.run(LoggingDemoApplication.class, args); } @Override public void run(String... args) { logger.info("Application started successfully."); logger.debug("This debug message will not appear because level is INFO."); } } # application.properties logging.file.name=logs/myapp.log logging.level.root=INFO
Common Pitfalls
1. Log file not created: This happens if the directory does not exist or the path is incorrect. Make sure the folder exists or Spring Boot has permission to create it.
2. Logs not appearing in file: Check that logging.file.name or logging.file.path is set correctly and not overridden elsewhere.
3. Using both logging.file.name and logging.file.path: Avoid setting both at the same time as it can cause conflicts.
# Wrong: setting both properties logging.file.name=logs/app.log logging.file.path=logs # Right: use only one logging.file.name=logs/app.log
Quick Reference
| Property | Description | Example Value |
|---|---|---|
| logging.file.name | Full path to the log file | logs/myapp.log |
| logging.file.path | Directory for default log file spring.log | logs |
| logging.level.root | Set global log level | INFO |
| logging.level.com.example | Set log level for package | DEBUG |