ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring Boot] Kotlin으로 REST API 만들기(3) - Logback 설정
    Spring Boot/Kotlin으로 REST API 만들기 2022. 10. 27. 09:52
    반응형

    Kotlin으로 REST API 만들기(3) - Logback 설정

    1. Logback 이란?
    Logback "자바 오픈소스 로깅 프레임워크"로 SLF4J의 구현체입니다. 스프링 부트의 기본으로 설정되어 있어서 의존성을 추가하지 않아도 사용 가능합니다.

    2. Logback 사용법
    LoggerFactory 클래스의 getLogger 메소드를 통해 Logger 객체를 생성하여 로깅하는 방법

    package com.example.springbootrestapi.web.controller
    
    import com.example.springbootrestapi.domain.TodoRequest
    import com.example.springbootrestapi.domain.TodoResponse
    import com.example.springbootrestapi.service.TodoService
    import org.slf4j.LoggerFactory
    import org.springframework.http.MediaType
    import org.springframework.web.bind.annotation.PostMapping
    import org.springframework.web.bind.annotation.RequestBody
    import org.springframework.web.bind.annotation.RestController
    import javax.servlet.http.HttpServletRequest
    import javax.servlet.http.HttpServletResponse
    
    @RestController
    class TodoController(
      val todoService: TodoService
    ) {
    
      private val log = LoggerFactory.getLogger(TodoController::class.java)
    
      /**
       * To-Do 조회
       */
      @PostMapping(
        value = ["/api/todos"],
        consumes = [MediaType.APPLICATION_JSON_VALUE],
        produces = [MediaType.APPLICATION_JSON_VALUE]
      )
      fun getTodos(
        request: HttpServletRequest,
        response: HttpServletResponse,
        @RequestBody todoRequest: TodoRequest
      ): MutableList<TodoResponse> {
        log.info("todoRequest:[{}]", todoRequest.toString())
        return todoService.getTodos(todoRequest)
      }
    }

     

    3. 로그 레벨
    로그에 설정할 수 있는 레벨은 총 5가지로 설정한 레벨 이상의 로그를 출력합니다. 예를 들어 로그 레벨 설정을 "INFO"로 하였을 경우 "TRACE", "DEBUG" 레벨은 출력되지 않습니다. 
    TRACE  <  DEBUG  <  INFO  <  WARN  <  ERROR
    TRACE : TRACE 레벨은 DEBUG 레벨보다 상세한 정보를 나타냅니다.
    DEBUG : 프로그램을 디버깅하기 위한 정보를 표시합니다.
    INFO  : 상태 변경과 같은 정보성 로그를 표시합니다.
    WARN  : 처리 가능한 문제, 향후 시스템 에러의 원인이 될 수 있는 경고성 메시지를 나타냅니다.
    ERROR : 요청을 처리하는 중 오류가 발생한 경우 표시합니다.

    4. profiles 설정
    profile 별로 로그 타입 및 레벨을 설정하기 위해서 application.yml에 profiles를 설정하세요.

    # server 설정
    server:
      port: 9091
    
    ---
    # datasource 설정
    spring:
      datasource:
        hikari:
          driver-class-name: com.mysql.cj.jdbc.Driver
          jdbc-url: jdbc:mysql://localhost:3306/sample?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC
          username: sample
          password: password1!
    
    ---
    # profiles 설정
    spring:
      profiles:
        active: local
        group:
          local: logging-type-condole, logging-level-local
          dev: logging-type-file, logging-level-dev


    5. logback-spring.xml 추가
    src/main/resources 폴더에 logback-spring.xml를 추가한 후 로그 타입 및 레벨을 설정하세요.

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
    
      <!-- log file path -->
      <property name="LOG_PATH" value="logs" />
      <!-- log file name -->
      <property name="LOG_FILE_NAME" value="springboot_rest_api" />
      <!-- pattern -->
      <property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] [%-5level] %logger{36} - %msg%n" />
    
      <!-- Profile 별로 로그 타입을 설정 -->
      <springProfile name="logging-type-console">
        <appender name="PROFILE-APPENDER" class="ch.qos.logback.core.ConsoleAppender">
          <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${LOG_PATTERN}</pattern>
          </encoder>
        </appender>
      </springProfile>
      <springProfile name="logging-type-file">
        <appender name="PROFILE-APPENDER" 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>
    
          <!-- Rolling 정책 -->
          <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- .gz,.zip 등을 넣으면 자동 일자별 로그파일 압축 -->
            <fileNamePattern>${LOG_PATH}/${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>30</maxHistory>
            <!--<MinIndex>1</MinIndex>
            <MaxIndex>10</MaxIndex> -->
          </rollingPolicy>
        </appender>
      </springProfile>
    
      <!-- Profile 별로 로그 레벨을 설정 -->
      <springProfile name="logging-level-local">
        <!--특정 패키지 로그 레벨 설정-->
        <property name="LOG_LEVEL_root" value="DEBUG"/>
        <property name="LOG_LEVEL_com.example.springbootrestapi" value="DEBUG"/>
        <property name="LOG_LEVEL_com.zaxxer.hikari" value="DEBUG"/>
      </springProfile>
      <springProfile name="logging-level-dev">
        <property name="LOG_LEVEL_root" value="INFO"/>
        <property name="LOG_LEVEL_com.example.springbootrestapi" value="INFO"/>
        <property name="LOG_LEVEL_com.zaxxer.hikari" value="INFO"/>
      </springProfile>
    
      <!-- com.example.springbootrestapi -->
      <logger name="com.example.springbootrestapi"
        level="${LOG_LEVEL_com.example.springbootrestapi}"
        additivity="false">
        <appender-ref ref="PROFILE-APPENDER"/>
      </logger>
      <!-- hikari -->
      <logger name="com.zaxxer.hikari"
        level="${LOG_LEVEL_com.zaxxer.hikari}"
        additivity="false">
        <appender-ref ref="PROFILE-APPENDER"/>
      </logger>
    
      <!-- 로그 레벨 설정 -->
      <root level="${LOG_LEVEL_root}">
        <appender-ref ref="PROFILE-APPENDER" />
      </root>
    
    </configuration>


    6. 로그 확인
    application.yml에서 설정한 spring.profiles를 변경하면서 로그를 확인하세요.
    6_1. spring.profiles.active가 local일 때 콘솔 화면에서 로그가 출력되는지 확인하세요

    6_2. spring.profiles.active가 dev일 때 파일이 생성되고 로그가 출력되는지 확인하세요.

     

    소스 코드는 Github Repository - https://github.com/tychejin1218/kotlin-springboot-rest-api.git (branch : section03) 를 참조하세요.

    [IntelliJ] GitHub에서 프로젝트 복사하기(Get from Version Control) - https://tychejin.tistory.com/325

    반응형

    댓글

Designed by Tistory.