日志界别动态调整2

package ***.cbb.log;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerRepository;

/**
 * 日志级别修改类,可以不停机(tomcat不需要重启)实现对日志记录级别的修改,
 * 并即时生效。
 * @author jianfeng.lu
 *
 */
public final class LogLevelChanger
{
  private static final Logger logger = Logger.getLogger(LogLevelChanger.class);
  private static LogLevelChanger instance;

  public static synchronized LogLevelChanger getInstance()
  {
    if (null == instance)
      instance = new LogLevelChanger();
    return instance;
  }

  public boolean changeLogLevel(String paramString)
  {
    if ((null == paramString) || ("".equals(paramString.trim())))
    {
      logger.warn("[amulog] changeLogLevel() strLevel is empty");
      return false;
    }
    if ("Debug".equalsIgnoreCase(paramString))
    {
      logger.getLoggerRepository().getRootLogger().setLevel(Level.DEBUG);
      return true;
    }
    if ("Info".equalsIgnoreCase(paramString))
    {
      logger.getLoggerRepository().getRootLogger().setLevel(Level.INFO);
      return true;
    }
    if ("Warn".equalsIgnoreCase(paramString))
    {
      logger.getLoggerRepository().getRootLogger().setLevel(Level.WARN);
      return true;
    }
    if ("Error".equalsIgnoreCase(paramString))
    {
      logger.getLoggerRepository().getRootLogger().setLevel(Level.ERROR);
      return true;
    }
    if ("DEFAULT".equalsIgnoreCase(paramString))
    {
      logger.getLoggerRepository().getRootLogger().setLevel(getDefaultLogLevel());
      return true;
    }
    logger.debug("[amulog] changeLogLevel() exit");
    return false;
  }

  private Level getDefaultLogLevel()
  {
    logger.debug("[amulog] getDefaultLogLevel() enter.");
    Level localLevel = null;
    String str = LogMgrHelper.getInstance().getDefaultLogLevel();
    if ("error".equalsIgnoreCase(str))
      localLevel = Level.ERROR;
    else if ("warn".equalsIgnoreCase(str))
      localLevel = Level.WARN;
    else if ("info".equalsIgnoreCase(str))
      localLevel = Level.INFO;
    else if ("debug".equalsIgnoreCase(str))
      localLevel = Level.DEBUG;
    else
      localLevel = Level.ERROR;
    logger.debug("[amulog] getDefaultLogLevel() leave.");
    return localLevel;
  }

  public String getLogLevel()
  {
    String str = logger.getLoggerRepository().getRootLogger().getLevel().toString();
    if ("Debug".equalsIgnoreCase(str))
      str = "Debug";
    if ("Info".equalsIgnoreCase(str))
      str = "Info";
    if ("Warn".equalsIgnoreCase(str))
      str = "Warn";
    if ("Error".equalsIgnoreCase(str))
      str = "Error";
    return str;
  }
}

你可能感兴趣的:(日志界别动态调整2)