log4j自定义输出级别和输出信息

log4j自定义输出级别和输出信息

  • 1.在web.xml中添加一个过滤器
  • 2.过滤器Log4jFilter.java
  • 3.自定义日志级别过滤器CustomLogFilter.java
  • 4.自定义日志级别CustomLog.java
  • 5.配置log4j.xml输出
  • 6.测试日志输出TestLogController.java
  • 7.测试结果

相关文章链接:

SSM框架搭建Web项目

log4j.xml配置详解

我们定义一个CUSTOMLOG1级别,自定义输出信息为访问者ip和属性attr。

1.在web.xml中添加一个过滤器


  <filter>
    <filter-name>Log4jFilterfilter-name>
    <filter-class>cn.com.mydemo.interceptor.Log4jFilterfilter-class>
  filter>
  <filter-mapping>
    <filter-name>Log4jFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

2.过滤器Log4jFilter.java

package cn.com.mydemo.interceptor;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.MDC;

/**
 * @Description 日志过滤器
 * @author jjy
 * @create 2019-06-19
 */
public class Log4jFilter implements Filter{
     

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
     
		//获取访问者ip
		String ip = request.getRemoteAddr();
		//log4j通过访问MDC中存入的键值对获取自定义属性,写法为%X{ip}(ip为MDC放入的key)
		MDC.put("ip", ip);
		
		try {
     
			chain.doFilter(request, response);
		} catch (Exception e) {
     
			e.printStackTrace();
		}
		//清空MDC
		if(MDC.getContext() != null) {
     
			MDC.getContext().clear();
		}
	}
	
	@Override
	public void destroy() {
     
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
     
	}
}

3.自定义日志级别过滤器CustomLogFilter.java

package cn.com.mydemo.interceptor;

import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggingEvent;

/**
 * @Decription 自定义日志级别过滤器
 * @author jjy
 * @create 2019-06-19
 */
public class CustomLogFilter extends Filter{
     

	boolean acceptOnMatch = false;
	private String levelMin;
	private String levelMax;
	
	public boolean isAcceptOnMatch() {
     
		return acceptOnMatch;
	}
	public void setAcceptOnMatch(boolean acceptOnMatch) {
     
		this.acceptOnMatch = acceptOnMatch;
	}
	public String getLevelMin() {
     
		return levelMin;
	}
	public void setLevelMin(String levelMin) {
     
		this.levelMin = levelMin;
	}
	public String getLevelMax() {
     
		return levelMax;
	}
	public void setLevelMax(String levelMax) {
     
		this.levelMax = levelMax;
	}
	@Override
	public int decide(LoggingEvent paramLoggingEvent) {
     
		int inputLevel = paramLoggingEvent.getLevel().toInt();
		if(inputLevel >= getLevel(levelMin) && inputLevel <= getLevel(levelMin)) {
     
			return 0;
		}
		
		return -1;
	}
	
	private int getLevel(String level) {
     
		level = level.toUpperCase();
		if(level.equals("CUSTOMLOG1")) {
     
			return LevelType.CUSTOMLOG1.getType();
		}
		if(level.equals("OFF")) {
     
			return LevelType.OFF.getType();
		}
		if(level.equals("FATAL")) {
     
			return LevelType.FATAL.getType();
		}
		if(level.equals("ERROR")) {
     
			return LevelType.ERROR.getType();
		}
		if(level.equals("INFO")) {
     
			return LevelType.INFO.getType();
		}
		if(level.equals("WARN")) {
     
			return LevelType.WARN.getType();
		}
		if(level.equals("DEBUG")) {
     
			return LevelType.DEBUG.getType();
		}
		if(level.equals("ALL")) {
     
			return LevelType.ALL.getType();
		}
		
		return LevelType.OFF.getType();
	}
	
	private static enum LevelType {
     
		OFF(2147483647),
		FATAL(50000),
		ERROR(40000),
		WARN(30000),
		INFO(20000),
		DEBUG(10000),
		ALL(-2147483648),
		
		CUSTOMLOG1(30050);
		
		int type;
		
		public int getType() {
     
			return type;
		}
		
		private LevelType(int type) {
     
			this.type = type;
		}
	}
}

4.自定义日志级别CustomLog.java

package cn.com.mydemo.interceptor;


import org.apache.log4j.Level;
import org.apache.log4j.net.SyslogAppender;

/**
 * @Decription 自定义日志级别
 * @author jjy
 * @create 2019-06-19
 */
package cn.com.infosec.ra.system.interceptor;


import org.apache.log4j.Level;
import org.apache.log4j.net.SyslogAppender;

public class CustomLog extends Level{
     
	
	private static final long serialVersionUID = 1L;

	private CustomLog(int level, String levelStr, int syslogEquivalent) {
     
		super(level, levelStr, syslogEquivalent);
	}
	
	//自定义级别名称,以及级别范围 
	public static final Level CUSTOMLOG1 = new CustomLog(30051, "CUSTOMLOG1", SyslogAppender.LOG_LOCAL0);
}

5.配置log4j.xml输出

我们将自定义级别单独输出一个文件,在log4j添加以下代码

<appender name="customlog1" class="org.apache.log4j.DailyRollingFileAppender">
    
    <param name="File" value="${catalina.base}/logs/mydemo/customlog1.log"/>
    <param name="Append" value="true"/>
    
    <param name="DatePattern" value="yyyy-MM-dd"/>
    
    <layout class="org.apache.log4j.PatternLayout">
      
      <param name="ConversionPattern" value="[%d{yyy-MM-dd HH:mm:ss,SSS}] [%c] [%M] [%L] [%X{attr}] - [%m] %n"/>
    layout>
    
    <filter class="cn.com.mydemo.interceptor.CustomLogFilter">
      
      <param name="LevelMin" value="CUSTOMLOG1" />
      <param name="LevelMax" value="CUSTOMLOG1" />
    filter>
  appender>

在root节点中添加以下代码

<appender-ref ref="customlog1"/>

log4j自定义输出级别和输出信息_第1张图片

6.测试日志输出TestLogController.java

package cn.com.mydemo.controller;

import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.mydemo.interceptor.CustomLog;

@Controller
public class TestLogController {
     

	private static Logger logger = Logger.getLogger(TestLogController.class);
	
	@RequestMapping(value = "/testLog")
	public String testLog() {
     
		MDC.put("attr", "自定义属性");
		logger.log(CustomLog.CUSTOMLOG1, "自定义日志级别");
		
		return "login";
	}
}

7.测试结果

在这里插入图片描述

你可能感兴趣的:(Java,Web,log4j,自定义输出)