首頁 > 軟體

SpringBoot設定log4j輸出紀錄檔的案例講解

2022-11-25 14:01:16

下文筆者講述SpringBoot設定log4j的方法分享,如下所示

SpringBoot紀錄檔輸出

springboot框架中預設使用logback進行紀錄檔輸出
當然它也可以設定其它的紀錄檔框架

SpringBoot設定log4j

Springboot設定log4j的方法:

   1.新增log4j.properties組態檔
   2.初始化組態檔

設定log4j檔案

 新增log4j.properties組態檔
 組態檔新增的路徑
   在工程src/main/resources下

檔案內容

#log4j.rootLogger=CONSOLE,info,error,DEBUG
log4j.rootLogger=info,error,CONSOLE,DEBUG

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender     
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout     
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n     
      
log4j.logger.info=info
log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
log4j.appender.info.layout=org.apache.log4j.PatternLayout     
log4j.appender.info.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n  
log4j.appender.info.datePattern='.'yyyy-MM-dd
log4j.appender.info.Threshold = info   
log4j.appender.info.append=true   
#log4j.appender.info.File=/home/java265project/logs/info/api_services_info
log4j.appender.info.File=/Users/java265project/logs/info/api_services_info

log4j.logger.error=error  
log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.layout=org.apache.log4j.PatternLayout     
log4j.appender.error.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n  
log4j.appender.error.datePattern='.'yyyy-MM-dd
log4j.appender.error.Threshold = error   
log4j.appender.error.append=true   
#log4j.appender.error.File=/home/java265project/logs/error/api_services_error
log4j.appender.error.File=/Users/java265project/logs/error/api_services_error

log4j.logger.DEBUG=DEBUG
log4j.appender.DEBUG=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DEBUG.layout=org.apache.log4j.PatternLayout     
log4j.appender.DEBUG.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n  
log4j.appender.DEBUG.datePattern='.'yyyy-MM-dd
log4j.appender.DEBUG.Threshold = DEBUG   
log4j.appender.DEBUG.append=true   
#log4j.appender.DEBUG.File=/home/java265project/logs/debug/api_services_debug
log4j.appender.DEBUG.File=/Users/java265project/logs/debug/api_services_debug

### Debug
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
注意事項:
    1.log4j.properties檔案中
      當部署線上環境,需要釋放掉註釋語句,並註釋線下設定語句。
      #log4j.appender.info.File=/home/java265project/logs/info/api_services_info
     log4j.appender.info.File=/Users/java265project/logs/info/api_services_info
    2.紀錄檔設定涉及三個級別:info、error、debug

例:

初始化log4j設定

springboot啟動是通過main入口函數
需在main入口函數中設定log4j初始化

public class App {
	private static final Logger logger = LoggerFactory.getLogger(App.class);	
	@Value("${server.port}")
	private int port;
	@Value("${server.sessionTimeout}")
	private int sessionTimeout;
	static {
		try{
		   // 初始化log4j
		   String log4jPath = "";
		   if(Constant.LOG_MODE == 1){
			   // 設定線上地址
			   log4jPath = App.class.getClassLoader().getResource("").getPath()+"java265project/config/log4j.properties";
			   logger.info("Log4j線上生產模式初始化。。。");	
		   }else{
			   // 設定本地地址
			   log4jPath = App.class.getClassLoader().getResource("").getPath()+"log4j.properties";
			   logger.info("Log4j線下開發模式初始化。。。");	
		   }		   		   
		   logger.info("初始化Log4j。。。。");	
		   logger.info("path is "+ log4jPath);	
		   PropertyConfigurator.configure(log4jPath);
		}catch (Exception e){			  
			  logger.error(e.toString());	
		}
    }

	public static void main(String[] args) {
		
		final String[] temp = args;
		
		logger.info("oops: main入口函數編碼-" +System.getProperty("file.encoding"));
		
		if(Constant.LOG_MODE == 0){
			SpringApplication.run(App.class, args);
			logger.info("oops: 線下開發測試");		
		}else{
			logger.info("oops:" + args[0]);		
		}
							
		if(ArrayUtils.isNotEmpty(args))
	    {
	        // 如果你的應用程式,執行後不自動退出,那麼處理start時不要執行正常的程式碼,否則在部署測試 appctl.sh 的時候,會一直等待程序退出
	        if(args[0].equals("startup"))
	        {	            	            
	        	new Thread(
	        		new Runnable(){
	        			public void run(){
	        				System.out.println("啟動Mythread子執行緒");
	        				logger.info("啟動Mythread子執行緒");	
	        				SpringApplication.run(App.class, temp);		        	        
	        			}
	        	}).start();
	        	
	        	System.out.println("program startup");
	    		logger.info("program startup");		    		
	        }else if(args[0].equals("stop"))
	        {
	            System.out.println("program stop");
	            logger.info("program stop");		            
	        }else if(args[0].equals("restart"))
	        {
	            System.out.println("program restart");
	            logger.info("program restart");	
	        }else if(args[0].equals("status"))
	        {
	            System.out.println("program status");
	            logger.info("program status");	
	        }
	    }		 
	}

優化設定

可對log4j.properties檔案進行調整
使其設定更簡單

log4j.rootLogger=${log.root}

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n
      
log4j.logger.info=info
log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
log4j.appender.info.layout=org.apache.log4j.PatternLayout
log4j.appender.info.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n
log4j.appender.info.datePattern='.'yyyy-MM-dd
log4j.appender.info.Threshold = info
log4j.appender.info.append=true
log4j.appender.info.File=${log.base}/java265project/logs/info/api_services_info

log4j.logger.error=error
log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.layout=org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n
log4j.appender.error.datePattern='.'yyyy-MM-dd
log4j.appender.error.Threshold = error
log4j.appender.error.append=true
log4j.appender.error.File=${log.base}/java265project/logs/error/api_services_error

log4j.logger.DEBUG=DEBUG
log4j.appender.DEBUG=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DEBUG.layout=org.apache.log4j.PatternLayout
log4j.appender.DEBUG.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n
log4j.appender.DEBUG.datePattern='.'yyyy-MM-dd
log4j.appender.DEBUG.Threshold = DEBUG
log4j.appender.DEBUG.append=true
log4j.appender.DEBUG.File=${log.base}/java265project/logs/debug/api_services_debug

### Debug
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

與之相應的main函數新增如下程式碼,同時去掉static程式碼塊:

System.setProperty("log.root",Constant.LOG_ROOT_DAILY);			
System.setProperty("log.base",Constant.LOG_PATH_DAILY);

到此這篇關於SpringBoot設定log4j輸出紀錄檔的案例講解的文章就介紹到這了,更多相關SpringBoot設定log4j輸出紀錄檔內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com