티스토리 뷰

에러와 친해지기

에러와 친해지기 - logback

날따라해봐요요롷게 2022. 4. 15. 16:04

코드 작성 후 실행 시 테스트 코드로 모두 커버하지 못하는 영역이 있으며 (사실 테스트 코드로 대부분 커버를 해야한다... 아직 테스트 코드를 작성 할 줄 몰라서ㅎㅎㅎ)

테스트 코드를 제대로 작성하지 못하는 상황이라면 에러를 자세히 살펴보면서 프로그래밍을 진행해야한다.

에러를 콘솔에서 볼 수도 있지만, 대체적올 에러를 기억하고 비슷하게 발생하는 에러를 보기 위해서는 에러를 따로 모아서 관리하는게 좋겠다는 생각을 해보았다. 

그래서 logback을 이용하여 로그를 파일로 관리하는 방법을 알아보고 로그를 다양한 방법으로 관리하는 방법을 알아보자.

 


아래의 document를 살펴보면서 공부해보자.

https://docs.spring.io/spring-boot/docs/2.1.8.RELEASE/reference/html/howto-logging.html

 

83. Logging

Spring Boot has no mandatory logging dependency, except for the Commons Logging API, which is typically provided by Spring Framework’s spring-jcl module. To use Logback, you need to include it and spring-jcl on the classpath. The simplest way to do that

docs.spring.io

https://docs.spring.io/spring-boot/docs/2.1.8.RELEASE/reference/html/boot-features-logging.html#boot-features-logback-extensions

 

26. Logging

Spring Boot uses Commons Logging for all internal logging but leaves the underlying log implementation open. Default configurations are provided for Java Util Logging, Log4J2, and Logback. In each case, loggers are pre-configured to use console output with

docs.spring.io

 

"Spring Boot uses Commons Logging for all internal logging but leaves the underlying log implementation open. Default configurations are provided for Java Util Logging, Log4J2, and Logback. In each case, loggers are pre-configured to use console output with optional file output also available."

-> 스프링 부트는 모든 내부 로깅에 공통 로깅을 사용하지만 기본 로그 구현은 열어둔다. ~~ 각 경우 로거는 콘솔 출력이 사전 구성이며, 선택적 파일 출력도 사용할 수 있습니다.

 

 

logback 사용하는 방법 의존성 등록

: The simplest way to do that is through the starters, which all depend on spring-boot-starter-logging. For a web application, you need only spring-boot-starter-web

-> 원래는 spring-boot-starter-logging 을 의존성 등록을 해야 하지만, 스프링 부트의 업데이트 후 spring-boot-starter-web 를 등록하면 사용이 가능해진다.  

- Maven

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

- Gradle

implementation 'org.springframework.boot:spring-boot-starter-web'

 


Custom Log Configuration

The various logging systems can be activated by including the appropriate libraries on the classpath and can be further customized by providing a suitable configuration file in the root of the classpath or in a location specified by the following Spring Environment property: logging.config

-> 다양한 로깅 시스템은 클래스 경로에 적절한 라이브러리를 포함함으로써 활성화될 수 있으며 클래스 경로의 루트 또는 다음 Spring Environment 속성에 의해 지정된 위치에 적합한 구성 파일을 제공하여 추가로 사용자 지정할 수 있습니다.

 

Since logging is initialized before the ApplicationContext is created, it is not possible to control logging from @PropertySources in Spring @Configuration files. The only way to change the logging system or disable it entirely is via System properties.

-> 로깅은 ApplicationContext가 생성되기 전에 초기화되므로 Spring @Configuration 파일의 @PropertySources에서 로깅을 제어할 수 없습니다. 로깅 시스템을 변경하거나 완전히 비활성화하는 유일한 방법은 시스템 속성을 통해서만 가능합니다.

 

Logging SystemCustomization

Logback logback-spring.xml, logback-spring.groovy, logback.xml, or logback.groovy
Log4j2 log4j2-spring.xml or log4j2.xml
JDK (Java Util Logging) logging.properties

 

 

When possible, we recommend that you use the -spring variants for your logging configuration (for example, logback-spring.xml rather than logback.xml). If you use standard configuration locations, Spring cannot completely control log initialization.

-> 가능한 경우 로깅 구성에 -spring 변형(예: logback.xml 대신 logback-spring.xml)을 사용하는 것이 좋습니다. 표준 구성 위치를 사용하는 경우 스프링이 로그 초기화를 완전히 제어할 수 없습니다.

 

즉, classpath (resource 디렉토리 밑) 에 logback-spring.xml 을 파일을 생성하여 설정하면 된다.

 


Log Levels

All the supported logging systems can have the logger levels set in the Spring Environment (for example, in application.properties) by using logging.level.<logger-name>=<level> where level is one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL, or OFF. The root logger can be configured by using logging.level.root.

 

-> 지원되는 모든 로깅 시스템은 logging.level을 사용하여 Spring Environment(예: application.properties)에서 로거 수준을 설정할 수 있습니다. 여기서 level은 TRACE, DEBUG, INFO, WARN, ERROR, FATAL 또는 OFF 중 하나입니다. 
logging.level.root를 사용하여 설정할 수 있다.

 

: 로그 레벨은 TRACE   DEBUG  <  INFO  <  WARN   ERROR 와 같다.

1) ERROR : 요청을 처리하는 중 오류가 발생한 경우 표시한다.

2) WARN  : 처리 가능한 문제, 향후 시스템 에러의 원인이 될 수 있는 경고성 메시지를 나타낸다.

3) INFO  : 상태변경과 같은 정보성 로그를 표시한다.
4) DEBUG : 프로그램을 디버깅하기 위한 정보를 표시한다. 
5) TRACE : 추적 레벨은 Debug보다 훨씬 상세한 정보를 나타낸다. 

 

 - 로그에 설정할 수 있는 레벨은 총 5가지다.

 - 위의 순서대로 높은 레벨을 가진다. 출력 레벨의 설정에 따라 설정 레벨 이상의 로그를 출력 한다.

 - 예를 들어 로깅 레벨 설정을 "INFO"로 하였을 경우 "TRACE", "DEBUG" 레벨은 무시한다.

logging.level.root=warn
logging.level.org.springframework.web=debug
logging.level.org.hibernate=error

Spring EnvironmentSystem PropertyComments

logging.exception-conversion-word LOG_EXCEPTION_CONVERSION_WORD The conversion word used when logging exceptions.
logging.file LOG_FILE If defined, it is used in the default log configuration.
logging.file.max-size LOG_FILE_MAX_SIZE Maximum log file size (if LOG_FILE enabled). (Only supported with the default Logback setup.)
logging.file.max-history LOG_FILE_MAX_HISTORY Maximum number of archive log files to keep (if LOG_FILE enabled). (Only supported with the default Logback setup.)
logging.path LOG_PATH If defined, it is used in the default log configuration.
logging.pattern.console CONSOLE_LOG_PATTERN The log pattern to use on the console (stdout). (Only supported with the default Logback setup.)
logging.pattern.dateformat LOG_DATEFORMAT_PATTERN Appender pattern for log date format. (Only supported with the default Logback setup.)
logging.pattern.file FILE_LOG_PATTERN The log pattern to use in a file (if LOG_FILE is enabled). (Only supported with the default Logback setup.)
logging.pattern.level LOG_LEVEL_PATTERN The format to use when rendering the log level (default %5p). (Only supported with the default Logback setup.)
PID PID The current process ID (discovered if possible and when not already defined as an OS environment variable).

 


 

Logback-spring.xml은 appender와 logger 크게 두개로 구분된다.

appender 

 - log의 형태를 설정, 로그 메시지가 출력될 대상을 결정하는 요소

 (콘솔에 출력할지, 파일로 출력 할지 등의 설정)

 

- ch.qos.logback.core.ConsoleAppender : 콘솔에 로그를 찍음, 로그를 OutputStream에 작성하여 콘솔에 출력되도록 한다.

- ch.qos.logback.core.FileAppender : 파일에 로그를 찍음, 최대 보관 일 수 등를 지정할 수 있다.

- ch.qos.logback.core.rolling.RollingFileAppender : 여러개의 파일을 롤링, 순회하면서 로그를 찍는다.(FileAppender를 상속 받는다. 지정 용량이 넘어간 Log File을 넘버링 하여 나누어 저장할 수 있다.)

- ch.qos.logback.classic.net.SMTPAppender : 로그를 메일에 찍어 보낸다.

- ch.qos.logback.classic.db.DBAppender : DB(데이터베이스)에 로그를 찍는다. 

 

<configuration>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- encoders are assigned the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
    </encoder>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="STDOUT" />
  </root>
  </configuration>



root, logger

 - 설정한 appender를 참조하여 package와 level을 설정한다.

 

- root

 - 전역 설정이라고 볼 수 있다.
 - 지역적으로 선언된 logger 설정이 있다면 해당 logger 설정이 default로 적용된다.

 

- logger

 - 지역 설정이라고 볼 수 있다.
 - additivity 값은 root 설정 상속 유무 설정.(default = true)




아래의 코드는 에러로그를 파일로 보는 xml 설정이다.

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds">
    <springProfile name="local">
        <property resource="logback-local.properties"/>
    </springProfile>
    <springProperty scope="context" name="LOG_LEVEL" source="logging.level.root"/>
    <!-- log file path -->
    <property name="LOG_PATH" value="${log.config.path}"/>
    <!-- log file name -->
    <property name="LOG_FILE_NAME" value="${log.config.filename}"/>
    <!-- err log file name -->
    <property name="ERR_LOG_FILE_NAME" value="err_log"/>
    <!-- pattern -->
    <property name="LOG_PATTERN" value="%-5level %d{yy-MM-dd HH:mm:ss}[%thread] [%logger{0}:%line] - %msg%n"/>

    <!-- File Appender -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <!-- 파일경로 설정 -->
        <file>${LOG_PATH}/${LOG_FILE_NAME}.log</file>
    <!-- 출력패턴 설정-->
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${LOG_PATTERN}</pattern>
        </encoder>
    </appender>

    <!-- 에러의 경우 파일에 로그 처리 -->
    <appender name="Error" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>error</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <file>${LOG_PATH}/${ERR_LOG_FILE_NAME}.log</file>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${LOG_PATTERN}</pattern>
        </encoder>
        <!-- Rolling 정책 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- .gz,.zip 등을 넣으면 자동 일자별 로그파일 압축 -->
            <fileNamePattern>${LOG_PATH}/${ERR_LOG_FILE_NAME}.%d{yyyy-MM-dd}_%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <!-- 파일당 최고 용량 kb, mb, gb -->
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <!-- 일자별 로그파일 최대 보관주기(~일), 해당 설정일 이상된 파일은 자동으로 제거-->
            <maxHistory>60</maxHistory>
        </rollingPolicy>

    </appender>

    <!-- root레벨 설정 -->
    <root level="${LOG_LEVEL}">
<!--        <appender-ref ref="CONSOLE"/>-->
        <appender-ref ref="FILE"/>
        <appender-ref ref="Error"/>
    </root>

</configuration>

 


출처: https://goddaehee.tistory.com/206 [갓대희의 작은공간]

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함