Log4j2的使用入门

阅读更多

 

首先 从apache网站(http://logging.apache.org/log4j/2.x/javastyle.html)上下载相应的类库,如果只是使用最简单的功能也可以直接从附件中下载两个Jar包。

 

第二:在当前的类路径下面创建配置文件log4j2.xml 当然也可以用json配置; 

配置文件如下:



    
    
        
        
            
            
            
            
        
        
        
        
            
            
        
    
    
    
        
        
            
            
        
    

 

 

第三:在代码中通过下面这个语句获得logger

private static Logger logger = LogManager.getLogger(HttpSender.class.getName()); 

 

 

第四:具体使用如下:

public static void main(String[] args) {
		println("CopyRight By @Ben");
		//String URI = "http://192.168.141.10:18000/action=Train&Type=object&Db=applelogoobject&ImagePath=E:/images/traininglogo/1.png&Name=stand&UniqueName=1";
		
		logger.entry();
		logger.debug("Application started!");
		String directory = "";
		try{
			directory = getValue("directory");
			logger.info("The directory is => "+directory);
		}catch(Exception e){
			logger.fatal("Failed to get directory", e.fillInStackTrace());
		}
		
		
		HttpSender sender = new HttpSender();
		String[] fileNames = null;
		try{
			fileNames = getSubFileNames(directory);
			logger.debug("Got "+fileNames.length+" file names => "+fileNames.toString());
		}catch(Exception e){
			logger.fatal("Failed to get filenames", e.fillInStackTrace());
		}
		
		
		String url = "";
		for(String name : fileNames){			
			url = sender.assembleURI(name, directory+name, getValue("Db"), "object", "Train");
			logger.info("Trained URL => "+url);
			sender.getSender(url);
			
		}
		
		logger.exit();
	}

 

第五:如果一切正常log输出如下:

CopyRight By @Ben
23:16:39.157 TRACE com.hp.ssit.jupiter.HttpSender 39 main - entry
23:16:39.162 DEBUG com.hp.ssit.jupiter.HttpSender 40 main - Application started!
23:16:39.163 INFO  com.hp.ssit.jupiter.HttpSender 44 main - The directory is => C:/share/HP/Autonomy/server/share/images/MI1/
23:16:39.166 DEBUG com.hp.ssit.jupiter.HttpSender 54 main - Got 110 file names => [Ljava.lang.String;@39f645e4
23:16:39.167 INFO  com.hp.ssit.jupiter.HttpSender 63 main - Trained URL => http://192.168.141.10:18000/action=Train&Type=object&Db=xiaomi&ImagePath=C:/share/HP/Autonomy/server/share/images/MI1/IMG_20150205_111916.jpg&Name=stand&UniqueName=IMG_20150205_111916.jpg
23:16:41.201 INFO  com.hp.ssit.jupiter.HttpSender 124 getSender - SUCCESS
23:16:49.767 TRACE com.hp.ssit.jupiter.HttpSender 68 main - exit

 

 

 

 

 

  • log4j-api-2.1.jar (130.4 KB)
  • 下载次数: 4
  • log4j-core-2.1.jar (805.4 KB)
  • 下载次数: 3

你可能感兴趣的:(log)