Sunny

J2EE和前端的技术分享

logback系列之七:继承RollingFileAppender,保存自定义文件名的日志

继承类:
package com.hk3t.air.system.log;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.rolling.RollingFileAppender;

import com.hk3t.air.utils.MyConstants;

/**
 * @author Sunny 
 *
 * 2016-8-23
 */
public class UserFileAppender extends RollingFileAppender<ILoggingEvent> {
	
	private String currentlyActiveFile;
	
	@Override
	protected void subAppend(ILoggingEvent event){
		
		if(currentlyActiveFile == null){
			currentlyActiveFile = getFile();
		}
		
		String activeFile = currentlyActiveFile;
		if(event.getMdc() != null){
			if(event.getMdc().get(MyConstants.LOG_USER_KEY) != null && event.getMdc().get(MyConstants.LOG_FILEPATH_KEY) != null){
				activeFile = event.getMdc().get(MyConstants.LOG_FILEPATH_KEY);
			}else{
				if(event.getMdc().get(MyConstants.LOG_USER_KEY) != null){
					activeFile = activeFile.replace("{LOG_USER}", event.getMdc().get(MyConstants.LOG_USER_KEY));
				}
				if(event.getMdc().get(MyConstants.LOG_IP_KEY) != null){
					activeFile = activeFile.replace("{LOG_IP}", event.getMdc().get(MyConstants.LOG_IP_KEY));
				}
			}
		}
		
		setFile(activeFile);
		start();
		super.subAppend(event);
	}
}

XML配置

	<appender name="USERFILE"  class="com.hk3t.system.log.UserFileAppender">
	
	    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
			<level>INFO</level>
	    </filter>
	    
            <filter class="com.hk3t.system.log.UserNameFilter"></filter>
		
            <file>${log.base}/user/user_{LOG_USER}_{LOG_IP}.log</file> 
        
        <!-- 
        	无法归档user.log日志,只有当session和ip都相同时(即文件名相同)。才会进行回滚的操作 
	        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">  
	            <FileNamePattern>${log.base}/%d{yyyy-MM-dd}_user_log.log</FileNamePattern>
	            <minIndex>1</minIndex> 
	            <MaxHistory>2</MaxHistory> 
	        </rollingPolicy>
        -->  
        <encoder>
            <pattern>%date [%contextName] [%marker] [%thread] [%X{LOG_IP}] [%X{LOG_USER}] %-5level %logger{80} - %msg%n</pattern>  
        </encoder>
        <append>true</append>  
    	<prudent>false</prudent>    
    </appender>


阅读更多
版权声明:看完觉得好的。请留个脚印,证明你来过 https://blog.csdn.net/qq592304796/article/details/52350613
个人分类: logback
上一篇windows下强制杀死tomcat进程
下一篇logback系列之八:自定义Pattern模板
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭