spring 5.1 이후) loging message 출력하기

리팩토링 벨로그·2022년 9월 30일
0

spring 5.1 이후

logging message 출력하기

spring 5.1 이후에서는 info level)console에서는 logging message가 뜨지 않는다.

해결책

step 1. configure the parent logger and console handler하기 위한 bean을 생성한다.

application context를 위한 parent logger level을 set 해주는 클래스-얘는 console handler에게도 logging level을 지정해준다. 이는 logger level을 FINE으로 해준다. 더 자세한 로깅 정보를 위해서, logging level을 FINEST로 지정할 수 있다. 이와 관련된 자세한 정보는 http://www.vogella.com/tutorials/Logging/article.html

이 클래스는 또한 actual configuration을 handle 하기 위한 초기화 메서드를 가지고 있다. 이 초기화 메서드는 bean이 생성되고 의존성이 주입(dependencies injected)되면 실행된다.

File: applicationContext.xml (snippet)

package com.luv2code.springdemo;
 
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
 
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
public class MyLoggerConfig {
 
	private String rootLoggerLevel;
	private String printedLoggerLevel;
	
	public void setRootLoggerLevel(String rootLoggerLevel) {
		this.rootLoggerLevel = rootLoggerLevel;
	}
 
	public void setPrintedLoggerLevel(String printedLoggerLevel) {
		this.printedLoggerLevel = printedLoggerLevel;
	}
 
	public void initLogger() {
 
		// parse levels
		Level rootLevel = Level.parse(rootLoggerLevel);
		Level printedLevel = Level.parse(printedLoggerLevel);
		
		// get logger for app context
		Logger applicationContextLogger = Logger.getLogger(AnnotationConfigApplicationContext.class.getName());
 
		// get parent logger
		Logger loggerParent = applicationContextLogger.getParent();
 
		// set root logging level
		loggerParent.setLevel(rootLevel);
		
		// set up console handler
		ConsoleHandler consoleHandler = new ConsoleHandler();
		consoleHandler.setLevel(printedLevel);
		consoleHandler.setFormatter(new SimpleFormatter());
		
		// add handler to the logger
		loggerParent.addHandler(consoleHandler);
	}
	
}

step 2. Spring XML config 파일에서 bean을 configure한다.

XML configure file에서 뒤따라 오는 bean entry를 추가해준다. 이는 이게 첫번째 bean임을 보장하여 맨 먼저 이니셜라이즈 된다. 맨 먼저 bean이 이니셜라이즈 됨으로써, 모든 logging 트래픽을 얻게 될 것이다. 만약 다른 bean보다 더 늦게 config file에 해주면, initial logging message의 일부를 놓칠 수 있다.

File: applicationContext.xml (snippet)

<!-- 
	Add a logger config to see logging messages.		
	- For more detailed logs, set values to "FINEST"
	- For info on logging levels, see: http://www.vogella.com/tutorials/Logging/article.html
 -->
    <bean id="myLoggerConfig" class="com.luv2code.springdemo.MyLoggerConfig" init-method="initLogger">
    	<property name="rootLoggerLevel" value="FINE" />
    	<property name="printedLoggerLevel" value="FINE"/>
    </bean>

코드 원본 github) https://gist.github.com/darbyluv2code/cfb16c2fd1825a947d8faca3724b47a9

참고 Udemy Spring & Hibernate for Beginners 24강 문서

profile
글 다시 씁니다.

0개의 댓글