1. gradle 설정
spring-boot-stater-logging exclude 처리
spring-boot-stater-log4j2 추가
plugins {
id 'java'
id 'org.springframework.boot' version '3.1.2'
id 'io.spring.dependency-management' version '1.1.2'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
java {
sourceCompatibility = '17'
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
all {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-log4j2'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
}
tasks.named('test') {
useJUnitPlatform()
}
2. log4j2.xml 설정
jobId를 기준으로 로그파일 생성되게끔 Routing Appender 생성
<Configuration status="INFO">
<Properties>
<Property name="LOG_FORMAT">%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n</Property>
<Property name="baseDir">/Users/beomun-park/IdeaProjects/logs</Property>
</Properties>
<Appenders>
<Routing name="Routing">
<Routes pattern="$${ctx:jobId}">
<Route>
<RollingFile name="Rolling-${ctx:jobId}"
fileName="${baseDir}/thread-${ctx:jobId}.log"
filePattern="${baseDir}/thread-${ctx:jobId}.log.%d{yyyy-MM-dd}">
<PatternLayout pattern="${LOG_FORMAT}"/>
<TimeBasedTriggeringPolicy/>
</RollingFile>
</Route>
</Routes>
</Routing>
<Console name="Console" target="SYSTEM_OUT" follow="true">
<PatternLayout pattern="%-5level [%F:%L]- %msg%n" />
</Console>
</Appenders>
<Loggers>
<logger name="org.springframework" level="info" additivity="false" >
<AppenderRef ref="Console" />
</logger>
<Root level="INFO">
<AppenderRef ref="Routing"/>
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
3. ThreadContext 에 jobId 입력
요청마다 jobId를 부여하여 log를 분리
public static void main(String[] args) {
SpringApplication.run(CustomAppenderSampleApplication.class, args);
ThreadContext.put("jobId", "jobId1");
log.info("thread1 log");
ThreadContext.put("jobId", "jobId2");
log.info("thread2 log");
}
4. 결과
$ ls
thread-jobId1.log thread-jobId2.log
'개발 > 스프링 프레임워크' 카테고리의 다른 글
[Spring Boot] JPA + PostgreSQL 연결 (1) | 2024.04.19 |
---|---|
[Spring Boot] JPA, AuditorAware 사용하여 사용자정보 자동 입력 (1) | 2023.07.12 |
[Spring Boot] AutoConfigureMockMvc 사용하여 Controller 테스트 (0) | 2023.07.04 |
[Spring Boot] H2 + JPA 세팅 (1) | 2022.07.21 |
[Spring Secutiry] Invalid CSRF token found for... (0) | 2020.09.15 |