2019独角兽企业重金招聘Python工程师标准>>>
直接看代码。
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;@Controller
@RequestMapping(value = "/log4j")
public class Log4jController {private Map<String, Logger> log4jLoggers = new HashMap<>();private Map<String, AppenderSkeleton> log4jAppenders = new HashMap<>();@PostConstructpublic void init() {loadLog4j();}private void loadLog4j() {Enumeration<?> loggers = LogManager.getLoggerRepository().getCurrentLoggers();//获取所有loggerwhile (loggers.hasMoreElements()) {Object elem = loggers.nextElement();if (elem instanceof org.apache.log4j.Logger) {org.apache.log4j.Logger log4j = (org.apache.log4j.Logger) elem;log4jLoggers.put(log4j.getName(), log4j);Enumeration<?> allAppenders = log4j.getAllAppenders();//获取logger相关的appenderwhile (allAppenders.hasMoreElements()) {Object apd = allAppenders.nextElement();if (apd instanceof AppenderSkeleton) {AppenderSkeleton appender = (AppenderSkeleton) apd;log4jAppenders.put(appender.getName(), appender);}}}}}@RequestMapping(value = "/setLoggerLevel")@ResponseBodypublic String setLoggerLevel(HttpServletRequest request) {String logName = request.getParameter("name");String levelStr = request.getParameter("level");Level level = Level.toLevel(levelStr, null);org.apache.log4j.Logger log4j = log4jLoggers.get(logName);if (log4j == null) {return "没有相应的logger[" + logName + "]存在";}if (level == null) {return "没有相应的日志级别[" + levelStr + "]存在";}log4j.setLevel(level);return "将日志logger[" + logName + "]设置为" + level.toString() + "模式";}@RequestMapping(value = "/setAppenderLevel")@ResponseBodypublic String setAppenderLevel(HttpServletRequest request) {String appenderName = request.getParameter("name");String levelStr = request.getParameter("level");Level level = Level.toLevel(levelStr, null);Response response = new Response();AppenderSkeleton appender = log4jAppenders.get(appenderName);if (appender == null) {return "没有相应的appender[" + appenderName + "]存在";}if (level == null) {return "没有相应的日志级别[" + levelStr + "]存在";}appender.setThreshold(level);return "将日志appender[" + appenderName + "]设置为" + level.toString() + "模式";}
}