动态修改日志级别

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
import org.apache.log4j.LogManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Enumeration;
import java.util.List;

public class DynamicLog {
        private static Logger logger = LoggerFactory.getLogger(DynamicLog.class);

        public static void main(String[] args) throws MessagingException {

            //1.logback
            LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
            //获取应用中的所有logger实例
            List loggerList = loggerContext.getLoggerList();

            //遍历更改每个logger实例的级别,可以通过http请求传递参数进行动态配置
            for (ch.qos.logback.classic.Logger logger:loggerList){
                logger.setLevel(Level.toLevel("ERROR"));
            }

            //2.log4j
            Enumeration enumeration = LogManager.getCurrentLoggers();
            while (enumeration.hasMoreElements()){
                org.apache.log4j.Logger logger = (org.apache.log4j.Logger) enumeration.nextElement();
                logger.setLevel(org.apache.log4j.Level.toLevel("error"));
            }

            //3.log4j2
            Collection notCurrentLoggerCollection = org.apache.logging.log4j.core.LoggerContext.getContext(false).getLoggers();
            Collection currentLoggerCollection = org.apache.logging.log4j.core.LoggerContext.getContext().getLoggers();
            Collection loggerCollection = notCurrentLoggerCollection;
            loggerCollection.addAll(currentLoggerCollection);
            for (org.apache.logging.log4j.core.Logger logger:loggerCollection){
                logger.setLevel(org.apache.logging.log4j.Level.toLevel("error"));
            }
            logger.info("log info");
            logger.error("log error");
        }
}

你可能感兴趣的:(动态修改日志级别)