tools & libs/로깅

[logging] log4j2 설정 및 사용

  • -
반응형

이번 포스트에서는 log4j2를 사용해 보자. log4j2도 slf4j를 구현하고 있기 때문에 사용법은 logback과 거의 동일하다. 따라서 설정을 살펴보고 logback에서 했던 설정을 그대로 log4j2에서 해보는 것을 목표로 한다.

https://logging.apache.org/log4j/2.x/

 

Log4j –

We share below some highlights from Log4j features. Batteries included Log4j bundles a rich set of components to assist various use cases. Appenders targeting files, network sockets, databases, SMTP servers, etc. Layouts that can render CSV, HTML, JSON, Sy

logging.apache.org

 

설정

 

의존성 추가

log4j2를 사용하려면 다음의 log4j-slf4j2-impl 만 있으면 된다. 이 녀석도 내부적으로 slf4j-api를 포함하고 있다.

<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-slf4j2-impl</artifactId>
  <version>2.22.0</version>
</dependency>

 

log4j2.xml 파일 작성

log4j2를 위한 설정 파일 log4j2.xml은 아래 경로에서 참조할 수 있다.

https://logging.apache.org/log4j/2.x/manual/configuration.html

 

Log4j – Configuring Log4j 2

Configuration Inserting log requests into the application code requires a fair amount of planning and effort. Observation shows that approximately 4 percent of code is dedicated to logging. Consequently, even moderately sized applications will have thousan

logging.apache.org

 

문서의 내용을 바탕으로 log4j2.xml을 생성하면 다음과 같다.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
  <Properties>
    <Property name="LOG_DIR">./logs</Property>
  </Properties>
  <Appenders>
    <Routing name='Routing'>
      <Routes pattern="$${sd:type}">
        <Route>
          <RollingFile name="rollingFile" fileName="${LOG_DIR}/application.log"
                       filePattern="${LOG_DIR}/application.%d{MM-dd}.log.gz">
            <PatternLayout>
              <Pattern>%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n</Pattern>
            </PatternLayout>
            <Policies>
              <TimeBasedTriggeringPolicy interval="1" />
              <SizeBasedTriggeringPolicy size="3GB" />
            </Policies>
            <DefaultRolloverStrategy max="30"/>
          </RollingFile>
        </Route>
      </Routes>
    </Routing>
    
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} %X %msg%n" />
    </Console>
  </Appenders>
  <!-- 대상별 레벨 및 출력 방향 설정 -->
  <Loggers>
    <!-- root는 전체를 대상으로 한다. -->
    <Root level="trace">
      <AppenderRef ref="Console" />
      <AppenderRef ref="Routing" />
    </Root>
    <!-- 패키지 별로 레벨과 출력 방향을 조절할 수 있다. -->
    <Logger name="org.springframework" level="info">
      <AppenderRef ref="Console" />
    </Logger>
  </Loggers>
</Configuration>

좀 더 길어지긴 했지만 상세히 뜯어보면 logback에서 사용했던 개념이 그대로 다 들어가있음을 알 수 있다.

log4j2.xml
0.00MB

이전 글: https://goodteacher.tistory.com/174

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.