SpringBoot(6):LogBackを使用したグローバルログ処理


LogBackの概要
LogBackはLog 4 jの創始者が設計したもう一つのオープンソースログコンポーネントであり、SpringBootではログコンポーネントへの依存を個別に追加する必要はありません.xmlには次の依存があります.

			org.springframework.boot
			spring-boot-starter-web
		

LogBackの使用
Logbackのプロファイルを作成します.プロファイルの場所はアプリケーションです.properties(または.yml)で構成できます.
logging.config=classpath:logback-boot.xml
詳細コメントのプロファイルを次に示します.

      
          
      
      
          
              
            %d %p (%file:%line\)- %m%n    
              
            UTF-8     
              
          
      
      
      
          
        log/sys.log      
          
          
              
              
              
            log/sys.%d.%i.log   
               
            30     
                  
                    
                1KB      
                  
              
              
              
                  
                %d %p (%file:%line\)- %m%n    
                  
              
            UTF-8      
              
          
      
          
            
          
      
      
      
          
              
          
Logbackを構成した後、JAVAコードで使用できます.
private static Logger logger=LoggerFactory.getLogger(xxx.class/*   */);
これにより、ログアシスタントが取得され、プログラムの実行中に情報を出力することができます.
logger.info("  MyController!");
このようにすれば、Systemの過剰な使用を避けることができる.out.println();パフォーマンスに問題が発生しました.
エラースタック情報をログファイルに印刷エラースタック情報をログファイルに印刷すると、BUGのメンテナンスと解決に役立ちます.SpringBootでは@Controller Advice、@ExceptionHandlerの2つの注釈を使用して実現できます.その前に@InitBinder,@ModelAttribute,@ExceptionHandler(value=Exception.class)の3つの注釈の役割を紹介します.
package com.mkdlp.demo.controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

/**
 * controller    
 * @author mkdlp
 * @since 2018/1/29
 */
@ControllerAdvice
public class MyControllerAdvice {

    /**
     *      @RequestMapping    ,              
     * 
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {}

    /**
     *      Model ,   @RequestMapping       
     * 
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "Magical Sam");
    }

    /**
     *         
     * 
     * 
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map errorHandler(Exception ex) {
        Map map = new HashMap();
        map.put("code", 100);
        map.put("msg", ex.getMessage());
        return map;
    }

}
次に、グローバル例外を処理する方法を示します.
GlobalExceptionHandler.java
package com.springboot.study.ExceptionHandler;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.springboot.study.exception.MyRuntimeException;


@ControllerAdvice
public class GlobalExceptionHandler {
	
	private static Logger logger=LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
	  /**
     *         
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map errorHandler(Exception ex) {
    	logger.error("11111======="+getMessage(ex)+"=======");
        Map map = new HashMap();
        map.put("code", 100);
        map.put("msg", getMessage(ex));
        return map;
    }
    
    /**
     *           MyException.class
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MyRuntimeException.class)
    public Map myErrorHandler(MyRuntimeException ex) {
    	logger.error("======="+ex.getMsg()+"=======");
        Map map = new HashMap();
        map.put("code", ex.getCode());
        map.put("msg", ex.getMsg());
        return map;
    }
    
    public static String getMessage(Exception e) { 
        StringWriter sw = null;  
        PrintWriter pw = null;  
        try {  
            sw = new StringWriter();  
            pw = new PrintWriter(sw);  
            //           printWriter   
            e.printStackTrace(pw);
            pw.flush();  
            sw.flush();  
        } finally {  
            if (sw != null) {  
                try {  
                    sw.close();  
                } catch (IOException e1) {
                    e1.printStackTrace();  
                }  
            }  
            if (pw != null) {  
                pw.close();
            }
        }  
        return sw.toString();  
    }
}
では、エラースタック情報をログファイルに出力できます.