헤르메스 LIFE

[Spring Boot] Spring Boot Sample REST + Log4J2 본문

Spring Boot Framework

[Spring Boot] Spring Boot Sample REST + Log4J2

헤르메스의날개 2021. 1. 9. 14:14
728x90

개발환경

Spring Boot 2.2.4

JDK 1.8.0_202

REST

Postman : REST Client

 

목표

1. Spring Boot REST 환경

2. Log4j2 추가


기존 프로젝트( https://hermeslog.tistory.com/445?category=530345 )에 Logging 설정을 추가했습니다.

1. pom.xml 수정

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>SpringBootSample</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <!--
                 스프링 부트에서 Log4j2를 사용하기위해선 내부로깅에서 쓰이는 의존성을 제외해주어야 합니다.
                 기본적으로 Spring은 Slf4j라는 로깅 프레임워크를 사용합니다.
                 구현체를 손쉽게 교체할 수 있도록 도와주는 프레임 워크입니다.
                 Slf4j는 인터페이스고 내부 구현체로 logback을 가지고 있는데, 
                 Log4j2를 사용하기 위해 exclude 해야 합니다.
                 -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- Log4j2 로깅 구현체를 사용을 위해 Spring Boot Starter에서 지원해주는  log4j2 의존성을 추가 해줍니다. -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <!--  빌드 플러그인 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2. log4j2-sping.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration >
    <!--    해당 설정파일에서 사용하는 프로퍼티-->
    <Properties>
        <Property name="logNm">Spring Boot Sample</Property>
        <Property name="layoutPattern">%style{%d{yyyy/MM/dd HH:mm:ss,SSS}}{cyan} %highlight{[%-5p]}{FATAL=bg_red, ERROR=red,
            INFO=green, DEBUG=blue}  [%C] %style{[%t]}{yellow}- %m%n -</Property>
    </Properties>
    <!--    LogEvent를 전달해주는 Appender-->
    <Appenders>
        <Console name="Console_Appender" target="SYSTEM_OUT">
            <PatternLayout pattern="${layoutPattern}"/>
        </Console>
        <RollingFile name="File_Appender" fileName="logs/${logNm}.log" filePattern="logs/${logNm}_%d{yyyy-MM-dd}_%i.log.gz">
            <PatternLayout pattern="${layoutPattern}"/>
            <Policies>
                <SizeBasedTriggeringPolicy size="200KB"/>
                <TimeBasedTriggeringPolicy interval="1"/>
            </Policies>
            <DefaultRolloverStrategy max="10" fileIndex="min"/>
        </RollingFile>
    </Appenders>
    <!--    실제 Logger-->
    <Loggers>
        <Logger name="org.springframework" level="OFF"
                additivity="false">
            <AppenderRef ref="Console_Appender" />
            <AppenderRef ref="File_Appender"/>
        </Logger>
        <Logger name="com" level="INFO" additivity="false">
            <AppenderRef ref="Console_Appender" />
            <AppenderRef ref="File_Appender"/>
        </Logger>
        <Root level="INFO" additivity="false">
            <AppenderRef ref="Console_Appender"/>
            <AppenderRef ref="File_Appender"/>
        </Root>
    </Loggers>
</Configuration>

이번에는 application.properties 파일을 application.yml 로 변경해봤습니다.

logging:
  config: classpath:log4j2-spring.xml      # 로그설정파일

server:
  port: 8090                        # 서버 포트 변경

spring:
  http:
    encoding:
      charset: utf-8
      enabled: true
      force: true
  mvc:
    hiddenmethod:
      filter:
        enabled: true
  output:
    ansi:
      enabled: always                # 콘솔 창에 출력되는 로깅 메세지를 색으로 구분해서 출력

 

SLF4J 를 이용한 logging

@Slf4j Annotation 으로 사용하고, log.debug 로 출력합니다.

import com.sample.model.User;
import com.sample.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("")
    public List<User> getAllUsers() {
        log.debug("[UserController >> getAllUsers]");
        List<User> result = userService.getAllUsers();
        return result;
    }
}

@SLF4J 를 사용하지 않고 기본 클래스만을 사용해서 Log4j2 를 사용할 수 있습니다.

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

// [...]

private Logger logger = LogManager.getLogger(this.getClass());

import com.sample.model.User;
import com.sample.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    private Logger logger = LogManager.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    @GetMapping("")
    public List<User> getAllUsers() {
        logger.debug("{}", "[UserController >> getAllUsers] 1234 ");
        return userService.getAllUsers();
    }
}

 

참고 : www.baeldung.com/spring-boot-logging

 

Logging in Spring Boot | Baeldung

Learn how to easily configure the most popular logging solutions in a Spring Boot application.

www.baeldung.com

참고 : hermeslog.tistory.com/450

 

[Exception] SLF4J: Class path contains multiple SLF4J bindings

개발환경 Spring Boot 2.2.4 JDK 1.8.0_202 REST + log4j2 설정 시 아래와 같은 오류가 발생했습니다. SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/C:/Users/hermes..

hermeslog.tistory.com

참고 : hermeslog.tistory.com/448?category=302344

 

[Spring Boot] SLF4J를 이용한 Log 설정 시 주의점

출처 : 백기선님의 강의 www.youtube.com/watch?v=o2-JaRD9qQE&t=907s&ab_channel=springcamp.io 1. 중요 !!! - SLF4J ( Simple Logging Facade for Java ) 는 Interface 입니다. - Spring Boot 은 기본적으로 JC..

hermeslog.tistory.com

 

728x90