실전 개발자를 위한 Spring Framework Day20 (2회차)
트랜잭션과 로깅
1. 스프링 트랜잭션
선언적 트랜잭션 - 스프링은 선언적 트랜잭션 방식을 사용
- 어노테이션을 이용한 선언적 방식
- AOP를 이용한 선언적 방식
프로그램에 의한 트랜잭션 처리(권장되지 않음)
스프링에서 트랜잭션 처리 모범사례
- 선언적 방식에 의한 트랜잭션 처리
- 트랜잭션은 주로 서비스 메소드를 대상으로 한다
어노테이션에 의한 트랜잭션 처리
- @root-context.xml에 Transaction Manager를 설정
- <tx:annotation-driven/> 설정
<!-- Transaction Manager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
- 트랜잭션이 필요한 클래스나 메소드에 @Transactional 어노테이션 추가
- 주로 서비스 클래스의 메소드에 적용
AOP를 이용한 트랜잭션 설정
- 트랜잭션 매니저 설정
<!-- Transaction Manager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
- 트랜잭션 어드바이스 설정
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="delete*"/>
</tx:attributes>
</tx:advice>
- AOP설정
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* kr.co.company.hello.service.*Service.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>
</aop:config>
2. SLF4J와 Logback을 이용한 로그 남기기
JAVA 진영의 로깅툴
-
commons-logging
-
log4j
-
java util logging
-
logback
-
이전에는 log4j와 commons-logging이 주로 사용되었으나 최근 SLF4J 사용 비중이 커지고 있음
-
여러 오픈소스 프로젝트를 사용하다 보면 Logging Tool의 충돌이 발생할 수 있어 Logging Tool을 통일시켜야 한다
-
Logback Log 패턴
-
%thread - 실행 쓰레드 명
-
%msg - 로깅 내용
-
%n - 개행 문자(new line 출력)
-
%-5level - 로깅 레벨 출력, 고정폭(5자리), 로깅 레벨이 info일 경우 빈칸 하나 추가
-
%d{yyyy-MM-dd HH:mm:ss.SSS} - 로깅하고 있는 현재 시간, 시·분·초·밀리초
-
%logger - 패캐지 포함 클래스 정보
-
%logger{0} - 패키지를 제외한 클래스 이름만 출력
-
%method - 로깅하고 있는 클래스의 메소드
-
%line - 로깅하고 있는 클래스 소스의 line
로깅 레벨
-
[고] erro > warn > info > debug > trace [저]
-
레벨은 선택된 레벨과 해당 레벨보다 높은 모든 레벨의 로그를 출력한다(trace 선택 시 모든 로그 출력)