/* JFox, the OpenSource J2EE Application Server
 *
 * Copyright (C) 2002 huihoo.org
 * Distributable under GNU LGPL license
 * See the GNU Lesser General Public License for more details.
 */

package org.huihoo.jfox.logging;

import java.net.URL;
import javax.management.MBeanRegistration;
import javax.management.ObjectName;
import javax.management.MBeanServer;
import org.apache.log4j.Level;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Appender;
import org.apache.log4j.Layout;

/**
 * 
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class LogManager implements LogManagerMBean, MBeanRegistration {
  private static org.apache.log4j.Logger rootLogger = org.apache.log4j.LogManager.getRootLogger();
  private static final String configFile = "log4j.properties";

  static {
    _init();
  }

  private static void _init() {
    URL url = Thread.currentThread().getContextClassLoader().getResource(configFile);
    if(url != null) {
      PropertyConfigurator.configureAndWatch(configFile,1000);
    }
    else {
      rootLogger.addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
    }
    rootLogger.info(LogManager.class.getName() + " initialized.");
  }

  public ObjectName preRegister(MBeanServer mBeanServer, ObjectName objectName) throws Exception {
    if(objectName == null) {
      objectName = new ObjectName(LogManagerMBean.OBJECT_NAME);
    }
    return objectName;
  }

  public void postRegister(Boolean aBoolean) {

  }

  public void preDeregister() throws Exception {

  }

  public void postDeregister() {
    org.apache.log4j.LogManager.shutdown();
  }

  public void reset() {
    org.apache.log4j.LogManager.resetConfiguration();
    _init();
  }

  public void setLevel(String level) {
    rootLogger.setLevel(Level.toLevel(level));
  }

  public String getLevel() {
    return rootLogger.getLevel().toString();
  }

  public void setPattern(String appenderName, String pattern) {
    Appender appender = rootLogger.getAppender(appenderName);
    if(appender != null) {
      appender.setLayout(new PatternLayout(pattern));
    }
  }

  public String getPattern(String appenderName) {
    Appender appender = rootLogger.getAppender(appenderName);
    if(appender != null) {
      Layout layout = appender.getLayout();
      if((layout != null) && (layout instanceof PatternLayout)){
        return ((PatternLayout)layout).getConversionPattern();
      }
    }
    return "";

  }

}
