Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

자바 logger 사용법 #28

Open
kyupid opened this issue Dec 24, 2021 · 1 comment
Open

자바 logger 사용법 #28

kyupid opened this issue Dec 24, 2021 · 1 comment
Assignees
Labels
자바 학습 Extra attention is needed

Comments

@kyupid
Copy link
Owner

kyupid commented Dec 24, 2021

No description provided.

@kyupid kyupid added 학습 Extra attention is needed 자바 labels Dec 24, 2021
@kyupid kyupid self-assigned this Dec 24, 2021
@kyupid
Copy link
Owner Author

kyupid commented Jan 28, 2022

  • 스프링쓰면 slf4j와 logback을 쓸 수 있다
  • 로그레벨을 설정해서 로그를 관리할 수 있다
  • 로그 파일 작성은 application.yml 과 logback-spring.xml에서
  • logback-spring.xml에서 더 디테일한 설정을 할 수 있어서 프로덕트에 적용하기 낫다

질문1: 로그를 프로덕트 코드에 같이 넣어야하는 것인가? 예를 들어 서비스층에서 로그를 사용한다고 하자. 그러면 그 비즈니스 로직들 안에 로그가 섞이게 되는데 걷어내고 싶은 의지가 계속 생기기때문에 같이 써야라는 의문이 생김. 어쩔수 없는건가?

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;

@RestController
public class LogController {

    private final Logger logger = LoggerFactory.getLogger("LoggerController 의 로그");

    @GetMapping("/log")
    public void log() {
        logger.info("로깅 발생!");
    }
}
@Service
public class LogService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());

    public void log() {
        logger.trace("Trace");
        logger.debug("Debug");
        logger.info("Info");
        logger.warn("Warn");
        logger.error("Error");
    }
}
[2021-08-07 18:19:09:17317][http-nio-8080-exec-1] INFO  LogService - Info
[2021-08-07 18:19:09:17317][http-nio-8080-exec-1] WARN  LogService - Warn
[2021-08-07 18:19:09:17317][http-nio-8080-exec-1] ERROR LogService - Error
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 이 곳에 추가할 기능을 넣는다. -->
    <!--    appender(어디에 출력할 지)-->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>[%d{yyyy-MM-dd HH:mm:ss}:%-3relative][%thread] %highlight(%-5level) %cyan(%logger{36}) - %msg %n</Pattern>
        </layout>
    </appender>

    <appender name="INFO_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>./logs/info.log</file> <!-- 파일을 저장할 경로를 정한다 -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch> <!-- 해당 레벨만 기록한다. -->
            <onMismatch>DENY</onMismatch> <!-- 다른 수준의 레벨은 기록하지 않는다.(상위 레벨도 기록 안함), 상위 수준의 레벨에 대한 기록을 원하면 ACCEPT 로 하면 기록된다. -->
        </filter> <!-- 레벨별 필터링이 필요없을 경우 filter class 관련된 부분을 삭제하면 됨-->
        <encoder>
            <pattern>[%d{yyyy-MM-dd HH:mm:ss}:%-3relative][%thread] %-5level %logger{35} - %msg%n</pattern> <!-- 해당 패턴 네이밍으로 현재 로그가 기록됨 -->
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>./was-logs/info.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern> <!-- 해당 패턴 네이밍으로 이전 파일이 기록됨 -->
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>100MB</maxFileSize> <!-- 한 파일의 최대 용량 -->
            </timeBasedFileNamingAndTriggeringPolicy>
            <maxHistory>180</maxHistory> <!-- 한 파일의 최대 저장 기한 -->
        </rollingPolicy>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT"/>
    </root>

    <logger name="LogService" additivity="false"> <!-- 콘솔에 출력된 LogController 에 대해서 아래 작업을 실행한다.-->
        <level value = "DEBUG" /> <!-- DEBUG 레벨 이상에서만 실행한다. -->
        <appender-ref ref="INFO_LOG" />
<!--        <appender-ref ref="WARN_LOG" />-->
    </logger>

<!--    <logger name="org.hibernate.SQL" additivity="false">-->
<!--        <level value = "DEBUG" />-->
<!--        <appender-ref ref="DEBUG_LOG" />-->
<!--    </logger>-->
</configuration>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
자바 학습 Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant