개발자 구겹이

log4j 로 로깅하기 본문

java/springboot

log4j 로 로깅하기

@layers9 2025. 6. 19. 20:20

스프링부트 프로젝트는 기본적으로 logback을 사용해서 로깅한다고 함!

때문에

log4j로 교체하여 로깅하기 위해서는 logback이 작동하지 못하게 하고, log4j 관련 lib이 활성화되도록 해주어야 함

 

 

>>

 

1. 환경설정 [pom.xml] 

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>
    
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
     <groupId>org.bgee.log4jdbc-log4j2</groupId>
        <artifactId>log4jdbc-log4j2-jdbc4</artifactId>
        <version>1.16</version>
</dependency>

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.17.1</version>
    <scope>compile</scope>
</dependency>

 

2. 환경설정[src/main/resources/log4j2.xml] 파일 추가

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <File name="LogFile" fileName="logs/loggingforlog.log" append="true">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
        </File>

        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
    </Appenders>

    <Loggers>
        <!-- SnmpLogger 전용 설정 -->
        <Logger name="com.pws_01.iloveyou.log4j.Logger" level="info" additivity="false">
            <AppenderRef ref="LogFile"/>
            <AppenderRef ref="Console"/>
        </Logger>

        <!-- Root logger 설정 -->
        <Root level="info">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

 

3. 환경설정[application.properties]

logging.config=classpath:log4j2.xml

 

 

4. 로그파일에 패턴을 살리고 싶다면, 별개의 클래스를 만들어서 StringBuild해주기

 

 

 

 

#추가업로드예정⎛;c*•ヮ•⎞

 

!참고!

.xml 파일 내에 Appender > File >> PatternLayout 정의 없이 파일 로깅하면 xml형식의 로깅이 수행됨