/*
 * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
 * This software is the proprietary information of Sun Microsystems, Inc.
 * Use is subject to license terms.
 * 
 * Copyright 2004 Sun Microsystems, Inc.  Tous droits r?serv?s.
 * Ce logiciel est propri?t? de Sun Microsystems, Inc.
 * Distribu? par des licences qui en restreignent l'utilisation.
 *
 * ident        "@(#)MfLogService.java 1.15     04/09/24 SMI"
 *
 */


package com.sun.mfwk.util.log;

// J2SE
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.Handler;
import java.util.logging.FileHandler;
import java.util.logging.Filter;
import java.util.logging.SimpleFormatter;
import java.util.logging.XMLFormatter;


// Java ES-MF common config file
import com.sun.mfwk.config.*;

// for Logmanager stuff
import java.util.Enumeration;
import java.util.logging.LogManager;


/**
 * Java ES-MF Logging service
 */
public class MfLogService {

    private Handler fileHandler; 
    private static String logPattern = "MFWK.";
    private static Logger logger = Logger.getLogger(logPattern);


    /**
     * Creates a new <code>MfLogService</code> instance.
     *
     */
    public MfLogService(String logFileName) {
        init(logFileName);
    }



    /**
     * Init file handler
     *
     */
    protected void init(String logFileName) {
        
        try {
                               
            // retrieves common config file
            MfConfig commonConfig = MfConfig.getConfig();
          
            //creates the log file using the directory given in common config file
            //and the filename given as an arg            
            String logFile = new String(commonConfig.getProperty("mfwk.log.dir") + "/" + logFileName + ".%g");
            
            logger.info("LogFile is: " + logFile);	    
            
	    fileHandler = 
		new FileHandler(logFile,
                                (new Integer(commonConfig.getProperty("mfwk.log.maxsize"))).intValue(),
                                (new Integer(commonConfig.getProperty("mfwk.log.nbfiles"))).intValue(),
				false);

            //set log level into handler and logger
	    Level level = Level.parse(commonConfig.getProperty("mfwk.log.level"));
            logger.setLevel(level);
            fileHandler.setLevel(level);
	    
            //associates logFile to this logger (children wilwl inherit this logfile           
            logger.addHandler(fileHandler);
            
            //turns off logging into parent handlers sdtout (sdk) or cacao file (agent)
            logger.setUseParentHandlers(false);

            //BS TBD 
            //provides XML/simple logs
             Handler[] loggerHandlers = logger.getHandlers();
            for  (int i = 0; i<loggerHandlers.length; i++){
                if (commonConfig.getProperty("mfwk.log.format").compareTo("XML") == 0) {
                    loggerHandlers[i].setFormatter(new XMLFormatter());
                } else {
                    loggerHandlers[i].setFormatter(new SimpleFormatter());
                }
            }                                            

        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

     /**
     * Detaches the handler associated with this logger and closes it
     *
     */
    public void logServiceRemoveHandler() {
        logger.removeHandler(fileHandler);
        fileHandler.close();
    }

    /**
     * Gets a logger that is handled by Java ES-MF logging service .
     *
     */
    public static Logger getLogger(String name) {
	return Logger.getLogger(logPattern + name);
    }



    /**
     * Get the logging level.
     */
    public static Level getLoggingLevel() {
	return logger.getLevel();
    }

    /**
     * Set the logging level.
     */
    public static synchronized void setLoggingLevel(Level level) {

	try {
	    logger.setLevel(level);
	    Handler[] handler = logger.getHandlers();
	    for (int ii=0; ii<handler.length; ii++) {
		handler[ii].setLevel(level);
	    }
	} catch(Exception e) {
	    // Temporary!
            throw new RuntimeException(e.getMessage());
	}	
    }

}
    
