日志输出格式化(自定义)

需求为:需要用ELK进行日志分析,日志为json格式方便存储及查询
则实现:将日志打印时统一转换为json格式
实现步骤:

一:选择一个公共模块中的pom.xml 引入jar

		
			ch.qos.logback
			logback-classic
			1.2.3
		
		
			ch.qos.logback
			logback-core
			1.2.3
		
二:在该模块下创建类继承LayoutBase 并编写自定义日志格式化代码
public class PattenLayOutDeal extends LayoutBase {

	
    @Override
    public String doLayout(ILoggingEvent event) {
    	
        StringBuilder sb = new StringBuilder(); 
        sb.append("{");
        sb.append("\"date\":");
        sb.append("\"").append(new Timestamp(event.getTimeStamp())).append("\"");
        sb.append(", \"level\":");
        sb.append("\"").append(event.getLevel()).append("\"");
        sb.append(", \"thread\":");
        sb.append("\"").append(event.getThreadName()).append("\"");
        sb.append(", \"className\": ");
        sb.append("\"").append(event.getLoggerName()).append("\"");
        sb.append(",\"message\": ");
        String message = event.getFormattedMessage();
        String reqService = "";
        String reqMethod = "";
        if (event.getThrowableProxy() != null) {
            ExtendedThrowableProxyConverter throwableConverter = new ExtendedThrowableProxyConverter();
            throwableConverter.start();
            message = event.getFormattedMessage() + "" + 			throwableConverter.convert(event);
            throwableConverter.stop();
        }
        if (message!=null) {
            message =  message.replaceAll("\\\\", "");
            message =  message.replaceAll("\"","'");
        }
        sb.append("\"").append(message).append("\"");
        if(reqService != null && reqMethod != null) {
        	sb.append(reqService);
        	sb.append(reqMethod);
        }
        sb.append("}");
        sb.append(CoreConstants.LINE_SEPARATOR);
        return sb.toString();
    }
三:修改logback-spring.xml内容(这里贴个简单的)



    
 
    
	
	
        
             
             
            true
        
    

    
        ${COMMON_LOG_HOME}/${logging.app.name}.log
        
            ${COMMON_LOG_HOME}/${logging.app.name}-%d{yyyy-MM-dd}.%i.log
            30
            
                100MB
            
        
        
          
            
			true
        
    

        
		 
        
    

完结,启动看日志则为json格式了。

你可能感兴趣的:(我的学习记录)