-
Logging differs between development and production environments
- Development - devs need detailed logs for debugging
- Production - keep logs minimal to preserve system performance, security, and disk space
-
Use
@Profileorspring.profiles.active -
To separate configurations in Logback by using
<springProfile>in the logging configuration file -
logging
-
db 설정
Example structure (yml files)
- In Spring Boot, you can create test-specific configuration files under
src/test/resourcesto separate the test environment completely from production. This allows safe and predictable testing.
src
├── main
│ └── resources
│ ├── application.yml
│ ├── application-dev.yml
│ ├── application-test.yml
│ ├── application-prod.yml
│ └── logback-spring.yml
Active profiles for testing
- Spring allows you to create
application-{profile}.ymlfiles and activate specific profiles during testing to apply corresponding settings. - Here are the different ways to activate Spring profiles for testing (pick one)
- Dev and Prod yaml settings for logging + testing: application-test.yml
- Before choosing to do any of these, you should create
application-test.ymlinsrc/test/resources(look above)
- Before choosing to do any of these, you should create
@ActiveProfiles
@SpringBootTest
@ActiveProfiles("test")
class UserServiceTest {
// test code
}- Applying
@ActiveProfiles("test")on a test class activates theapplication-test.ymlprofile only for that test.
src/test/resources/application.yml
- You can set the default profile globally here
spring:
profiles:
active: test- This sets the
testprofile as the default for all tests
build.gradle - specifying system property
// build.gradle
test {
systemProperty 'spring.profiles.active', 'test'
}- In Gradle, this passes
spring.profiles.active=testas a system property when running tests.
Using @TestPropertySource
@SpringBootTest
@TestPropertySource(
properties = "spring.profiles.active=test",
locations = "classpath:custom-test.properties"
)
class CustomPropertyTest {
// test code
}@TestPropertySourcelets you specify a custom properties file or inline properties for a test.- In practice,
@ActiveProfilesand setting the default profile insrc/test/resources/application.ymlare the most common ways to configure test profiles.
Directory & yaml Files Example (log/test)
src
├── main
│ └── resources
│ ├── application.yml
│ ├── application-dev.yml
│ ├── application-test.yml
│ ├── application-prod.yml
│ └── logback-spring.yml
application.yml- Common settings and profile activationapplication-dev.yml- Development environment settings onlyapplication-test.yml- Test environment settings onlyapplication-prod.yml- Production environment settings onlylogback-spring.yml- Common logging settings and profile-based logging configuration
application.yml
spring:
profiles:
active: dev # 실행 시 기본 활성화 프로필 (dev)
# db settings for production
datasource:
# Connect to a real MySQL database
url: jdbc:mysql://prod-db-server:3306/my_app
username: prod_user
password: ${PROD_DB_PASSWORD} # Loaded from environment variables
jpa:
hibernate:
ddl-auto: validate # Don't automatically change the real databaseapplication-dev.yml
- Spring Boot uses the naming convention of
application-{profile}.yml(or.properties) to load profile-specific configuration files automatically
logging:
level:
root: DEBUG
com.example.myapp: DEBUG
org.hibernate: WARN
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"application-test.yml
######### logging settings #########
logging:
level:
root: WARN
com.example.myapp: DEBUG
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"
######### db settings #########
spring:
# db settings for test
datasource:
# Use a fast, temporary in-memory database for each test run
url: jdbc:h2:mem:testdb
username: sa
password: password
jpa:
hibernate:
ddl-auto: create-drop # Create the schema at the start, drop it at the end
show-sql: true # Show SQL logs for debugging
main:
allow-bean-definition-overriding: true # Allow overriding beans in tests- uses an H2 in-memory database for testing
- sets Hibernate SQL logging to
DEBUGlevel ddl-auto: create-dropoption ⇒ ensures tables are created at test start and dropped afterward
application-prod.yml
logging:
level:
root: WARN
com.example.myapp: INFO
file:
name: logs/myapp.loglogback-spring.yml
- Logging in Spring - Logback: Rolling Policy
yamlfiles are for general Spring Boot properties and basic logging levels, but not for complex Logback setup such as rolling policies.- offers a limited YAML-based wrapper configuration for some logging properties, including rolling policies, but it is not a full replacement for the XML config
- NOT a full alternative to XML config
# 공통 및 운영환경용 롤링 설정 포함
logging:
file:
name: logs/myapp.log
logback:
rollingpolicy:
file-name-pattern: logs/myapp.%d{yyyy-MM-dd}.log
max-history: 90 # 보관 기간: 90일
total-size-cap: 10GB # 최대 저장 용량: 10GB
clean-history-on-start: true # 애플리케이션 시작 시 오래된 로그 삭제logback-spring.ymlreplaces XML-based configuration and is automatically parsed by Spring Boot to apply logging settings.logging.logback.rollingpolicyis only supported inlogback-spring.yml, so do not declare it inapplication-*.yml.- Manage profile-specific logging levels (e.g., development, production) in
application-*.yml, and configure actual log file policies inlogback-spring.yml.
Conventions and good practices
Production: application-prod.yml
- You want to see only what’s necessary to monitor the health of the application and react to critical problems.
- High-volume logging can impact performance and fill up disk space quickly
- Good practices
- Root Log Level:
INFOorWARN: Set the default logging level toINFO.- This logs application startup messages, important events, and any custom
INFOlogs you’ve written. - Use
WARNif you want to be even more conservative and only log potential issues.
- This logs application startup messages, important events, and any custom
- File Logging: Always log to a file in production.
- The console is unreliable for long-term storage and analysis. You should configure the log file location and rotation policy to prevent it from growing too large.
- Specific Packages:
ERRORorWARN: Suppress verbose logs from external libraries.- For example, database-related libraries like Hibernate or JDBC are often very chatty. In production, you generally only need to see their
ERRORorWARNlogs.
- For example, database-related libraries like Hibernate or JDBC are often very chatty. In production, you generally only need to see their
- Structured Logging: Consider using a structured format like JSON for easier ingestion and analysis by log aggregation tools (e.g., Elasticsearch, Splunk). Example:
- Root Log Level:
logging:
level:
root: INFO # Default level for all loggers
org.springframework: WARN # Suppress most Spring framework logs
org.hibernate.SQL: WARN # Suppress detailed Hibernate SQL logs
org.hibernate.type.descriptor.sql.BasicBinder: WARN # Suppress parameter binding info
com.yourcompany: INFO # Set your application's package to INFO
file:
name: /var/log/your-app/your-app.log # Log to a file
logback:
rollingpolicy:
max-file-size: 10MB # Rotate log file at 10MB
max-history: 10 # Keep up to 10 old log filesTest: application-test.yml
- You want to see enough detail to diagnose test failures without being overwhelmed. This is similar to development but often more focused
- Good Practices:
- Root Log Level:
INFOorWARN: Start with a moderate root level. - SQL Logging:
DEBUGorTRACE: This is where you need to be verbose. To debug a failing integration test, it’s invaluable to see the exact SQL queries being executed and their parameter values. - Application-specific:
DEBUG: Set your application’s package toDEBUGto see detailed logs about your business logic. - Console Only: It’s usually sufficient to log to the console (
stdout) during testing. File logging can be overkill and just creates more files to manage.
- Root Log Level:
logging:
level:
root: WARN # Suppress noise from non-essential libraries
com.yourcompany: DEBUG # Verbose logging for your code
org.hibernate.SQL: DEBUG # See all SQL statements
org.hibernate.type.descriptor.sql.BasicBinder: TRACE # See SQL parameter valuesDev: application-dev.yml
- You want to see everything to debug issues quickly - most verbose configuration
- Good Practices:
- Root Log Level:
INFO: A good starting point. You can go lower if you want to see even more framework logs. - Application-specific:
DEBUG: Your own code should be the priority. Set your base package toDEBUG. - SQL Logging:
DEBUG: Like in testing, seeing the SQL queries is extremely helpful during development. - Console Output: Console logging is perfect for development. It’s fast, and you can see real-time logs in your IDE.
spring.jpa.show-sql: Use this Spring Boot property (or the Hibernate equivalentformat_sql) to format and display SQL queries.
- Root Log Level:
# A common pattern is to have a base application.yml with shared settings,
# and this profile-specific file overrides only the logging.
# Assume that show-sql is in application.yml.
# spring.jpa.show-sql: true
logging:
level:
root: INFO
com.yourcompany: DEBUG # Your application's package
org.springframework.web: INFO # See Spring MVC mappings and other high-level info
org.hibernate.SQL: DEBUG # All executed SQL
org.hibernate.type.descriptor.sql.BasicBinder: TRACE # Parameter values