Language/Java
logback 로그 설정
건담아빠
2024. 10. 29. 10:51
P6spy문제
p6spy를 활용해서 로그를 설정해서 사용을 하였더니 문제가 발생하였다.
@Transactional(readOnly = true)
public void testReadOnly() {
}
이렇게 설정하게 되면
TransactionSynchronizationManager.isCurrentTransactionReadOnly()가 true이고 아래 ReplicationRoutingDataSource 로직에 따라 secondaries DB를 바로 보게 되어야 하는데 testReadOnly 메소드 안에서 TransactionSynchronizationManager.isCurrentTransactionReadOnly()를 찍어보면 true가 리턴되는데 ReplicationRoutingDataSource에 설정된 determineCurrentLookupKey에서는 false가 리턴되지 않아서 의도하지 않은 primary DB로 접근하게 되었다.
할일 많으니 정확한 원인은 나중에 찾고 급한대로 p6spy설정된 부분들을 모두 제거하고 logback방식으로 변경해보자.
@Slf4j
public class ReplicationRoutingDataSource extends AbstractRoutingDataSource {
private final ReadOnlyDataSourceCycle<Object> readOnlyDataSourceCycle = new ReadOnlyDataSourceCycle<>();
@Override
public void setTargetDataSources(Map<Object, Object> targetDataSources) {
super.setTargetDataSources(targetDataSources);
List<Object> readOnlyDataSourceLookupKeys = targetDataSources.keySet().stream().toList();
readOnlyDataSourceCycle.setReadOnlyDataSourceLookupKeys(readOnlyDataSourceLookupKeys);
}
@Override
public Object determineCurrentLookupKey() {
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
Object key = readOnlyDataSourceCycle.getReadOnlyDataSourceLookupKey();
return key;
}
// readOnly가 아니면 (null을 반환하면) defaultDatasource를 사용한다.
return null;
}
}
secondaries
Logback으로 변경
- logback.xml
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
...
<!-- Hibernate SQL 쿼리 로깅 설정 -->
<logger name="org.hibernate.SQL" level="DEBUG" additivity="false">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</logger>
...
</configuration>
- application.yml
spring:
jpa:
show-sql: true