본문 바로가기
매일코딩/Spring

27.springproject - log

by 인생여희 2016. 11. 18.
반응형

* 로깅툴을 사용하는 이유


- System.out.println() 명령어는 IO 리소스를 많이 사용하여 시스템이 느려질 수 있음


- 로그를 파일로 저장하여 분석할 필요가 있음




* 로깅툴의 종류


- commons-logging : 스프링 3에서 사용하던 로깅툴


- log4j : 효율적인 메모리 관리로 그동안 많이 사용되었음


- logback : log4j 보다 성능이 더 우수하여 최근에 많이 사용되고 있음




* SLF4J : logback을 사용하기 위한 인터페이스



from : http://edu.lifesoft.org/board/show.aspx?category=spring&idx=379&page=0




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
* 설정방법
 
 
 
1. pom.xml 의 slf4j-version 을 1.7.21 로 수정
 
 
 
    <properties>
 
        <java-version>1.8</java-version>
 
        <org.springframework-version>4.3.0.RELEASE</org.springframework-version>
 
        <org.aspectj-version>1.6.10</org.aspectj-version>
 
        <org.slf4j-version>1.7.21</org.slf4j-version>
 
    </properties>
 
 
 
2. pom.xml 에 라이브러리 추가
 
        <!-- logback 로깅 관련 -->
 
        <dependency>
 
            <groupId>org.slf4j</groupId>
 
            <artifactId>jcl-over-slf4j</artifactId>
 
            <version>1.7.21</version>
 
        </dependency>
 
        <dependency>
 
            <groupId>ch.qos.logback</groupId>
 
            <artifactId>logback-classic</artifactId>
 
            <version>1.1.7</version>
 
        </dependency>
 
cs




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
3. src/main/resources 에 logback.xml 파일 작성
 
 
 
<?xml version="1.0" encoding="UTF-8"?>
 
<configuration>
 
 
 
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
 
        <layout class="ch.qos.logback.classic.PatternLayout">
 
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-4level [%logger.%method:%line]-
 
                %msg%n</pattern>
 
        </layout>
 
    </appender>
 
 
 
    <appender name="LOGFILE"
 
        class="ch.qos.logback.core.rolling.RollingFileAppender">
 
        <file>/WEB-INF/logback.log</file>
 
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
 
            <fileNamePattern>logback.%d{yyyy-MM-dd}.log</fileNamePattern>
 
            <!-- 30일 지난 파일은 삭제한다. -->
 
            <maxHistory>30</maxHistory>
 
        </rollingPolicy>
 
        <encoder>
 
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-4level [%logger.%method:%line]
 
                - %msg %n</pattern>
 
        </encoder>
 
    </appender>
 
 
 
    <!-- 로그의 레벨( 지정된 로그 레벨 이상만 수집 ) : DEBUG < INFO < WARN < ERROR < FATAL -->
 
    <logger name="myweb" additivity="false">
 
        <level value="INFO" />
 
        <appender-ref ref="LOGFILE" />
 
        <appender-ref ref="CONSOLE" />
 
    </logger>
 
 
 
    <root>
 
        <level value="INFO" />
 
        <appender-ref ref="CONSOLE" />
 
    </root>
 
 
 
</configuration>
 
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
4. 로그를 수집할 클래스에 변수 선언
 
 
 
private static final Logger logger = LoggerFactory.getLogger(클래스이름.class);
 
 
 
private : 외부에서 로그를 가로채지 못하도록 하기 위해서
 
static final : 로그 내용이 바뀌지 않으므로
 
 
 
5. 로그를 수집할 method에서 로그 수집 명령어 호출 
 
 
 
logger.info("로그 타이틀",  출력할 값);
 
 
 
* 로그의 level
 
1. Debug : Debug, Info, Warn, Error 포함
 
2. Info : Info, Warn, Error 포함
 
3. Warn : Warn, Error 포함
 
4. Error : Error만 포함
 
 
 
<!-- logback 로깅 관련 -->
 
        <dependency>
 
            <groupId>org.slf4j</groupId>
 
            <artifactId>jcl-over-slf4j</artifactId>
 
            <version>1.7.21</version>
 
        </dependency>
 
        <dependency>
 
            <groupId>ch.qos.logback</groupId>
 
            <artifactId>logback-classic</artifactId>
 
            <version>1.1.7</version>
 
        </dependency>
        
        
        
        
        
        
        
@Controller // 
 
public class BoardController {
 
    // log fild
    private static final Logger Logger = LoggerFactory.getLogger(BoardController.class);
 
    
    
    @Inject
    BoardService boardService; // BoardServiceImpl�쓣 二쇱엯�떆�궡
 
    @RequestMapping("board/board_delete.do")
    public String board_delete(@RequestParam int idx) {
 
        boardService.boardDelete(idx);
        return "redirect:/board/board_list.do";
    }
 
    @RequestMapping("board/board_list.do")
    public String board_list(@RequestParam(defaultValue = "1"int curPage, Model model,
            @RequestParam(required = false, defaultValue = "username"String search_option,
            @RequestParam(required = false, defaultValue = ""String search) {
 
        /*
         * @RequestParam에 지정된 변수에 값이 넘어오지 않으면 400에러 발생 required=false 필수 입력항목이
         * 아님, 기본값은 required=true defaultValue= "기본값"
         */
 
        int count = boardService.boardCount(search_option, search);
 
        PageDAO pageDao = new PageDAO(count, curPage);
 
        int start = pageDao.getPageBegin();
        int end = pageDao.getPageEnd();
 
        List<BoardDTO> list = boardService.boardList(start, end, search_option, search);
 
        model.addAttribute("list", list);
 
        // 페이지 네비게이션 관련자료 저장
        model.addAttribute("page", pageDao);
 
        // 검색관련 정보 저장
        model.addAttribute("search_option", search_option);
        model.addAttribute("search", search);
 
        //log output
        Logger.info("pageinfo:" + pageDao);
 
        return "board/board_list";
 
    }
    
    
    
    
    
    
    -> if there is a problem ->maven -> updatemaven
    
    
    
    
    
cs




systemout.println() =====> loger


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.example.web03.aop;
 
import java.util.Arrays;
 
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
 
import com.example.web03.controller.board.BoardController;
 
//종단 관심 - 핵심적인 비즈니스 로직 join , buy,
//횡단관심(aspect) 공통적인 로직 (로그, 트랜젝션 등등)
// Advice - 횡단관심을 모든 코드에서 처리하지 않고 공통적으로 처리 할 수 있도록 지원하는 코드
 
@Component // 스프링에서 관리하는 빈
@Aspect // 스프링에서 관리하는 aop bean
 
public class LogAdvice {
    // 포인트컷 - before, after,실행 시점, around 실행 전후
    // 컨트롤러의 모든 method 실행 전후에 logPrint method가 호출됨
 
    // 로거 변수 만들기
    private static final Logger Logger = LoggerFactory.getLogger(LogAdvice.class);
 
    @Around("execution(* com.example.web03.controller..*Controller.*(..))"
            + " or execution(* com.example.web03.service..*Impl.*(..))"
            + " or execution(* com.example.web03.model..*Impl.*(..))")
    public Object logPrint(ProceedingJoinPoint joinPoint) throws Throwable {
 
        // 현재 시스템의 시간
        long startTime = System.currentTimeMillis();
 
        // 컨트롤러의 method가 실행됨
        Object result = joinPoint.proceed();
 
        // 클래스 이름
        String type = joinPoint.getSignature().getDeclaringTypeName();
        // method 이름
        String method = joinPoint.getSignature().getName();
        // 매개변수
        String args = Arrays.toString(joinPoint.getArgs());
 
        /*
         * System.out.println("클래스" + type); System.out.println("method" +
         * method); System.out.println("매개변수" + args);
         */
        // 로깅 툴을 이용한 로거 찍기
 
        Logger.info("클래스=" + type);
        Logger.info("method=" + method);
        Logger.info("매개변수=" + args);
 
        long endTime = System.currentTimeMillis();
 
        Logger.info("실행시간=" + (endTime - startTime));
        Logger.info("=================================================");
        /*
         * System.out.println("실행시간" + (endTime - startTime));
         * System.out.println(
         * "=================================================");
         */
        return result;
    }
}
cs


반응형

'매일코딩 > Spring' 카테고리의 다른 글

29.spring- detgul  (2) 2016.11.18
28.spring - hitup  (4) 2016.11.18
26.스프링프로젝트 - 페이징 처리  (6) 2016.11.17
25.스프링프로젝트 - aop  (6) 2016.11.17
24.스프링프로젝트 - download  (0) 2016.11.17

댓글