Search in sources :

Example 1 with Formatter

use of java.util.logging.Formatter in project OpenAM by OpenRock.

the class LogManager method readConfiguration.

/**
     * This method overrides the <code>readConfiguration</code> method in
     * JDK <code>LogManager</code> class.
     * The base class method resets the loggers in memory. This method
     * must add handlers to the loggers in memory according to the
     * new configuration.
     *
     * @throws IOException if there are IO problems reading the configuration.
     * @throws SecurityException if a security manager exists and if the caller
     * does not have <code>LoggingPermission("control")</code>.
     */
public final void readConfiguration() throws IOException, SecurityException {
    String[] xlogData = null;
    try {
        /*
             * This writeLock ensures that no logging threads will execute
             * a logger.log call after this point since they request for
             * a readLock.
             */
        Logger.rwLock.writeRequest();
        /*
             * This sync is for avoiding this thread snathing away
             * time slice from a thread executing getLogger() method
             * which is also sync on Logger.class
             * which may lead to two handlers being added to the same logger.
             */
        synchronized (Logger.class) {
            Enumeration loggerNames = getLoggerNames();
            LogManagerUtil.setupEnv();
            if (didFirstReadConfig && SystemProperties.isServerMode()) {
                oldLocation = getProperty(LogConstants.LOG_LOCATION);
                oldLevel = getProperty(LogConstants.LOGGING_LEVEL);
                oldSecurityStatus = getProperty(LogConstants.SECURITY_STATUS);
                oldBackend = getProperty(LogConstants.BACKEND);
                oldStatus = getProperty(LogConstants.LOG_STATUS_ATTR);
            }
            try {
                /*
                     * This change is done for deploying AM as a single
                     * war. In server mode we will always use our
                     * LogConfigReader. On the client side the
                     * the JVM property will define whether to use the
                     * LogConfigReader or the remote handlers. If no
                     * JVM property is set, the remote handlers will
                     * be used.
                     */
                if (SystemProperties.isServerMode()) {
                    LogConfigReader logConfigReader = new LogConfigReader();
                } else {
                    super.readConfiguration();
                }
                didFirstReadConfig = true;
            } catch (Exception ex) {
            /* no debug since our debugging system is not up. */
            } finally {
                LogManagerUtil.resetEnv();
            }
            if (isLocal) {
                securityStatus = false;
                readAllFields();
                readSelectedFieldSet();
                if (SystemProperties.isServerMode()) {
                    newLocation = getProperty(LogConstants.LOG_LOCATION);
                    newLevel = getProperty(LogConstants.LOGGING_LEVEL);
                    newSecurityStatus = getProperty(LogConstants.SECURITY_STATUS);
                    newBackend = getProperty(LogConstants.BACKEND);
                    newStatus = getProperty(LogConstants.LOG_STATUS_ATTR);
                }
                /*
                     * give all the pertinent values to decide why
                     * logging to the file was terminated.  still
                     * have to check that one of the attributes
                     * that changed would cause a "real" termination
                     * of logging to the files/tables in the current
                     * location (as opposed to just a buffer timer change,
                     * for instance).
                     */
                String[] logData = { oldLocation, newLocation, oldBackend, newBackend, oldSecurityStatus, newSecurityStatus, oldStatus, newStatus, oldLevel, newLevel };
                if (getProperty(LogConstants.BACKEND).equals("DB")) {
                    HANDLER = getProperty(LogConstants.DB_HANDLER);
                    FORMATTER = getProperty(LogConstants.DB_FORMATTER);
                    String driver = getProperty(LogConstants.DB_DRIVER);
                } else if (getProperty(LogConstants.BACKEND).equals("Syslog")) {
                    HANDLER = getProperty(LogConstants.SYSLOG_HANDLER);
                    FORMATTER = getProperty(LogConstants.SYSLOG_FORMATTER);
                } else if (getProperty(LogConstants.SECURITY_STATUS).equalsIgnoreCase("ON")) {
                    securityStatus = true;
                    HANDLER = getProperty(LogConstants.SECURE_FILE_HANDLER);
                    FORMATTER = getProperty(LogConstants.SECURE_ELF_FORMATTER);
                } else {
                    HANDLER = getProperty(LogConstants.FILE_HANDLER);
                    FORMATTER = getProperty(LogConstants.ELF_FORMATTER);
                }
                if (getProperty(LogConstants.BACKEND).equals("File")) {
                    if (SystemProperties.isServerMode() && (newLocation != null) && (oldLocation != null) && !oldLocation.equals(newLocation)) {
                        File dir = new File(newLocation);
                        if (!dir.exists()) {
                            if (!dir.mkdirs()) {
                                Debug.error("LogManager:readConfiguration:" + "Unable to create the new log " + "directory. Verify that the " + "process has necessary permissions");
                            }
                        }
                    }
                }
                boolean loggingInactive = (getProperty(LogConstants.LOG_STATUS_ATTR).equals(inactive));
                String strLogLevel = getProperty(LogConstants.LOGGING_LEVEL);
                try {
                    loggingLevel = Level.parse(strLogLevel);
                } catch (IllegalArgumentException iaex) {
                    // default
                    loggingLevel = Level.INFO;
                    Debug.error("LogManager:readConfiguration:" + "Log level '" + strLogLevel + "' unknown; setting to Level.INFO.");
                }
                if (loggingInactive) {
                    loggingLevel = Level.OFF;
                }
                xlogData = logData;
            } else {
                HANDLER = getProperty(LogConstants.REMOTE_HANDLER);
                if (HANDLER == null) {
                    HANDLER = LogConstants.DEFAULT_REMOTE_HANDER;
                }
                FORMATTER = getProperty(LogConstants.REMOTE_FORMATTER);
                if (FORMATTER == null) {
                    FORMATTER = LogConstants.DEFAULT_REMOTE_FORMATTER;
                }
            }
            Logger.resolveHostName = Boolean.valueOf(getProperty(LogConstants.LOG_RESOLVE_HOSTNAME_ATTR)).booleanValue();
            /*
                 * modify existing loggers in memory according
                 * to the new configuration
                 */
            loggerNames = getLoggerNames();
            while (loggerNames.hasMoreElements()) {
                String curEl = (String) loggerNames.nextElement();
                /* avoid root logger */
                if (!curEl.isEmpty() && !curEl.equals("global")) {
                    if (Debug.messageEnabled()) {
                        Debug.message("LogManager:readConfiguration:" + "Processing Logger: " + curEl);
                    }
                    /*
                         * remove all handlers and add new handlers for
                         * this logger
                         */
                    Logger l = (Logger) Logger.getLogger(curEl);
                    Handler[] handlers = l.getHandlers();
                    for (int i = 0; i < handlers.length; i++) {
                        handlers[i].close();
                        l.removeHandler(handlers[i]);
                    }
                    String handlerClass = LogManager.HANDLER;
                    Class clz = null;
                    Class[] parameters = { String.class };
                    Object[] parameterObjects = { l.getName() };
                    Constructor cons = null;
                    Handler h = null;
                    try {
                        clz = Class.forName(handlerClass);
                    } catch (Exception e) {
                        Debug.error("LogManager.readConfiguration:could not load " + handlerClass, e);
                    }
                    try {
                        cons = clz.getDeclaredConstructor(parameters);
                    } catch (Exception e) {
                        Debug.error("LogManager.readConfiguration:could not" + " instantiate" + handlerClass, e);
                    }
                    try {
                        h = (Handler) cons.newInstance(parameterObjects);
                    } catch (Exception e) {
                        Debug.error("LogManager.readConfiguration:could not" + " instantiate" + handlerClass, e);
                    }
                    String formatterClass = LogManager.FORMATTER;
                    Formatter f = null;
                    try {
                        f = (Formatter) Class.forName(formatterClass).newInstance();
                    } catch (Exception e) {
                        Debug.error("LogManager.readConfiguration:could not" + " instantiate Formatter " + formatterClass, e);
                    }
                    h.setFormatter(f);
                    l.addHandler(h);
                    /*
                         *  get the "iplanet-am-logging.<logfilename>.level
                         *  value for this file, if it's been added on the
                         *  server's advanced config page.
                         *
                         *  BUT: logging status set to Inactive means
                         *  all logging is turned Level.OFF
                         */
                    Level tlevel = loggingLevel;
                    if (loggingLevel != Level.OFF) {
                        String levelProp = LogConstants.LOG_PROP_PREFIX + "." + l.getName() + ".level";
                        String lvlStr = SystemProperties.get(levelProp);
                        if ((lvlStr != null) && (lvlStr.length() > 0)) {
                            try {
                                tlevel = Level.parse(lvlStr);
                            } catch (IllegalArgumentException iaex) {
                            // use value for all others
                            }
                        }
                    }
                    if (loggingLevel != null) {
                        // only if isLocal
                        // update logging level
                        l.setLevel(tlevel);
                    }
                }
            /* end of avoid rootlogger */
            }
        /* end of while(loggerNames.hasMoreElements) */
        }
    /* end of synchronized(Logger.class) */
    } finally {
        Logger.rwLock.writeDone();
    }
    if (SystemProperties.isServerMode() && isLocal) {
        checkStartLogs(xlogData);
        //Update the new configuration info in Monitoring handle also
        updateMonitConfigForLogService();
    }
}
Also used : Enumeration(java.util.Enumeration) Constructor(java.lang.reflect.Constructor) Formatter(java.util.logging.Formatter) Handler(java.util.logging.Handler) LogConfigReader(com.sun.identity.log.s1is.LogConfigReader) IOException(java.io.IOException) Level(java.util.logging.Level) File(java.io.File)

Example 2 with Formatter

use of java.util.logging.Formatter in project OpenAM by OpenRock.

the class Logger method processNewLoggerObject.

/**
     * To add handlers and formatters to the new logger object
     */
private static void processNewLoggerObject(Logger result) {
    Formatter formatter = null;
    String handlerClass = LogManager.HANDLER;
    String formatterClass = LogManager.FORMATTER;
    String levelProp = LogConstants.LOG_PROP_PREFIX + "." + result.logName + ".level";
    /*
         *  see if logging level for this file already defined.
         *  if not, then check AMConfig.properties.
         *  if not, then use Logging service config value.
         *  if not, then use default ("INFO")
         */
    String levelString = lm.getProperty(levelProp);
    if ((levelString == null) || !(levelString.length() > 0)) {
        levelString = SystemProperties.get(levelProp);
        if ((levelString == null) || !(levelString.length() > 0)) {
            levelString = lm.getProperty(LogConstants.LOGGING_LEVEL);
            if ((levelString == null) || !(levelString.length() > 0)) {
                levelString = LogConstants.DEFAULT_LOGGING_LEVEL_STR;
            }
        }
    }
    Level logLevel = null;
    try {
        logLevel = Level.parse(levelString);
    } catch (IllegalArgumentException iaex) {
        logLevel = LogConstants.DEFAULT_LOGGING_LEVEL;
    }
    result.setLevel(logLevel);
    //  but disabled logging in AMConfig.properties takes precedence
    String logStatus = lm.getProperty(LogConstants.LOG_STATUS_ATTR);
    if (logStatus != null && logStatus.startsWith("INACTIVE")) {
        logLevel = Level.OFF;
    }
    result.setLevel(logLevel);
    Class clz = null;
    Class[] parameters = { String.class };
    Object[] parameterObjects = { result.logName };
    Constructor cons = null;
    Handler handler = null;
    if (handlerClass == null) {
        Debug.error("Logger:processNewLoggerObject:" + "HandlerClass not in classpath ");
        return;
    }
    try {
        clz = Class.forName(handlerClass);
    } catch (Exception e) {
        Debug.error("Logger:processNewLoggerObject:" + "HandlerClass not in classpath: " + handlerClass, e);
        return;
    }
    try {
        if (clz != null) {
            cons = clz.getDeclaredConstructor(parameters);
        }
    } catch (Exception e) {
        Debug.error("Logger:processNewLoggerObject:" + "constructor parameter mismatch ", e);
        return;
    }
    try {
        if (cons != null) {
            handler = (Handler) cons.newInstance(parameterObjects);
        }
    } catch (Exception e) {
        Debug.error("Logger:processNewLoggerObject:" + "Could not instantiate handler: " + handlerClass, e);
        return;
    }
    if (formatterClass == null) {
        Debug.error("Logger:processNewLoggerObject:" + "formatterClass not in classpath ");
        return;
    }
    try {
        clz = Thread.currentThread().getContextClassLoader().loadClass(formatterClass);
    } catch (Exception e) {
        Debug.error("Logger:processNewLoggerObject:" + "Could not load Formatter Class: " + formatterClass, e);
        return;
    }
    try {
        if (clz != null) {
            formatter = (Formatter) clz.newInstance();
        }
    } catch (Exception e) {
        Debug.error("Logger:processNewLoggerObject:" + "Could not get Formatter instance " + formatterClass, e);
        return;
    }
    try {
        handler.setFormatter(formatter);
        result.addHandler(handler);
    } catch (Exception e) {
        Debug.error("Logger:processNewLoggerObject:" + "Unable to add Handler", e);
        return;
    }
    String filterClassName = lm.getProperty(LogConstants.FILTER_CLASS_NAME);
    try {
        if (filterClassName != null) {
            Filter filter = (Filter) Class.forName(filterClassName).newInstance();
            result.setFilter(filter);
        }
    } catch (Exception e) {
        Debug.error("Logger:processNewLoggerObject:" + "Could not set Filter: " + filterClassName, e);
    }
    result.setUseParentHandlers(false);
    resolveHostName = Boolean.valueOf(lm.getProperty(LogConstants.LOG_RESOLVE_HOSTNAME_ATTR)).booleanValue();
}
Also used : Filter(java.util.logging.Filter) Formatter(java.util.logging.Formatter) Constructor(java.lang.reflect.Constructor) Handler(java.util.logging.Handler) Level(java.util.logging.Level) MissingResourceException(java.util.MissingResourceException) IOException(java.io.IOException) SSOException(com.iplanet.sso.SSOException)

Example 3 with Formatter

use of java.util.logging.Formatter in project OpenAM by OpenRock.

the class FileHandler method publish.

/**
     * Format and publish a LogRecord.
     * <p>
     * This FileHandler is associated with a Formatter, which has to format the
     * LogRecord according to ELF and return back the string formatted as per 
     * ELF. This method first checks if the header is already written to the 
     * file, if not, gets the header from the Formatter and writes it at the 
     * beginning of the file.
     * @param lrecord the log record to be published.
     */
public void publish(LogRecord lrecord) {
    if (MonitoringUtil.isRunning() && fileLogHandlerForMonitoring != null) {
        fileLogHandlerForMonitoring.incHandlerRequestCount(1);
    }
    if (maxFileSize <= 0) {
        return;
    }
    if (!isLoggable(lrecord)) {
        return;
    }
    Formatter formatter = getFormatter();
    String message = formatter.format(lrecord);
    synchronized (this) {
        recordBuffer.add(message);
        if (recordBuffer.size() >= recCountLimit) {
            if (Debug.messageEnabled()) {
                Debug.message(fileName + ":FileHandler.publish(): got " + recordBuffer.size() + " records, writing all");
            }
            nonBlockingFlush();
        }
    }
}
Also used : Formatter(java.util.logging.Formatter)

Example 4 with Formatter

use of java.util.logging.Formatter in project ACS by ACS-Community.

the class ClientLogManagerTest method testLoggerStructure.

public void testLoggerStructure() {
    Logger containerLogger = clientLogManager.getLoggerForContainer("test");
    assertNotNull(containerLogger);
    Logger acsRemoteLogger = containerLogger.getParent();
    assertNotNull(acsRemoteLogger);
    assertFalse(acsRemoteLogger.getUseParentHandlers());
    Logger rootLogger = acsRemoteLogger.getParent();
    assertNotNull(rootLogger);
    assertNull(rootLogger.getParent());
    Handler[] handlers = containerLogger.getHandlers();
    assertTrue(handlers.length == 2);
    StdOutConsoleHandler localHandler = null;
    AcsLoggingHandler remoteHandler = null;
    for (Handler handler : handlers) {
        if (handler instanceof StdOutConsoleHandler) {
            localHandler = (StdOutConsoleHandler) handler;
        } else if (handler instanceof AcsLoggingHandler) {
            remoteHandler = (AcsLoggingHandler) handler;
        } else {
            fail("Unexpected handler type " + handler.getClass().getName() + " encountered.");
        }
    }
    assertNotNull(localHandler);
    assertNotNull(remoteHandler);
    Formatter localFormatter = localHandler.getFormatter();
    assertTrue("localFormatter should not be of type " + localFormatter.getClass().getName(), localFormatter instanceof ConsoleLogFormatter);
    Handler[] parentHandlers = acsRemoteLogger.getHandlers();
    assertTrue(parentHandlers.length == 0);
    assertEquals(AcsLogLevel.DELOUSE, remoteHandler.getLevel());
    containerLogger.info("I'm a good pedigree logger.");
}
Also used : ConsoleLogFormatter(alma.acs.logging.formatters.ConsoleLogFormatter) Formatter(java.util.logging.Formatter) Handler(java.util.logging.Handler) Logger(java.util.logging.Logger) ConsoleLogFormatter(alma.acs.logging.formatters.ConsoleLogFormatter)

Example 5 with Formatter

use of java.util.logging.Formatter in project j2objc by google.

the class MemoryHandlerTest method testFlush.

public void testFlush() {
    Filter filter = handler.getFilter();
    Formatter formatter = handler.getFormatter();
    writer.getBuffer().setLength(0);
    handler.flush();
    assertEquals(writer.toString(), "flush");
    assertEquals(handler.getFilter(), filter);
    assertEquals(handler.getFormatter(), formatter);
    assertNull(handler.getEncoding());
    assertNotNull(handler.getErrorManager());
    assertEquals(handler.getLevel(), Level.FINE);
    assertEquals(handler.getPushLevel(), Level.WARNING);
    assertTrue(handler.isLoggable(new LogRecord(Level.SEVERE, "test")));
}
Also used : Filter(java.util.logging.Filter) LogRecord(java.util.logging.LogRecord) SimpleFormatter(java.util.logging.SimpleFormatter) Formatter(java.util.logging.Formatter)

Aggregations

Formatter (java.util.logging.Formatter)50 LogRecord (java.util.logging.LogRecord)22 File (java.io.File)14 Logger (java.util.logging.Logger)13 IOException (java.io.IOException)12 Handler (java.util.logging.Handler)12 SimpleFormatter (java.util.logging.SimpleFormatter)12 FileHandler (java.util.logging.FileHandler)11 ConsoleHandler (java.util.logging.ConsoleHandler)7 JSONLogFormatter (fish.payara.enterprise.server.logging.JSONLogFormatter)6 Date (java.util.Date)6 ErrorManager (java.util.logging.ErrorManager)6 Test (org.junit.Test)6 Filter (java.util.logging.Filter)5 GFLogRecord (com.sun.common.util.logging.GFLogRecord)4 Config (edu.neu.ccs.pyramid.configuration.Config)4 SimpleDateFormat (java.text.SimpleDateFormat)4 Level (java.util.logging.Level)4 StreamHandler (java.util.logging.StreamHandler)4 EarlyLogHandler (com.sun.enterprise.module.bootstrap.EarlyLogHandler)3