Search in sources :

Example 46 with Formatter

use of java.util.logging.Formatter in project Payara by payara.

the class LogManagerService method getHandlerServices.

private Collection<Handler> getHandlerServices(Map<String, String> props) {
    Set<String> handlerServicesSet = new HashSet<String>();
    handlerServicesSet.add(GFFileHandler.class.getName());
    String[] handlerServicesArray = handlerServices.split(",");
    for (String handlerService : handlerServicesArray) {
        handlerServicesSet.add(handlerService);
    }
    List<Handler> handlers = habitat.getAllServices(Handler.class);
    List<Handler> result = new ArrayList<Handler>();
    List<Handler> customHandlers = new ArrayList<Handler>();
    GFFileHandler gfFileHandler = null;
    for (Handler handler : handlers) {
        String handlerClassName = handler.getClass().getName();
        if (handlerServicesSet.contains(handlerClassName)) {
            result.add(handler);
        }
        if (handlerClassName.equals(GFFileHandler.class.getName())) {
            gfFileHandler = (GFFileHandler) handler;
        } else if (!handlerClassName.equals(PayaraNotificationFileHandler.class.getName())) {
            customHandlers.add(handler);
        }
    }
    // Set formatter on custom handler service if configured
    for (Handler handler : customHandlers) {
        String handlerClassName = handler.getClass().getName();
        String formatterClassName = props.get(handlerClassName + ".formatter");
        Formatter formatter = getCustomFormatter(formatterClassName, gfFileHandler);
        if (formatter != null) {
            handler.setFormatter(formatter);
        }
    }
    return result;
}
Also used : PayaraNotificationFileHandler(fish.payara.enterprise.server.logging.PayaraNotificationFileHandler) Formatter(java.util.logging.Formatter) JSONLogFormatter(fish.payara.enterprise.server.logging.JSONLogFormatter) ArrayList(java.util.ArrayList) EarlyLogHandler(com.sun.enterprise.module.bootstrap.EarlyLogHandler) Handler(java.util.logging.Handler) PayaraNotificationFileHandler(fish.payara.enterprise.server.logging.PayaraNotificationFileHandler) ConsoleHandler(java.util.logging.ConsoleHandler) HashSet(java.util.HashSet)

Example 47 with Formatter

use of java.util.logging.Formatter in project Payara by payara.

the class PayaraMicroImpl method resetLogging.

/**
 * Reset the logging properties from the given file.
 * @param loggingProperty the location of the file to read from.
 */
private void resetLogging(String loggingProperty) {
    if (loggingProperty != null) {
        // we need to copy into the unpacked domain the specified logging.properties file
        File file = new File(loggingProperty);
        if (file.canRead()) {
            try {
                runtimeDir.setLoggingProperties(file);
            } catch (IOException ex) {
                LOGGER.log(Level.SEVERE, "Could not copy over logging properties file", ex);
            }
        }
        if (logToFile) {
            LOGGER.log(Level.WARNING, "logToFile command line option ignored as a logging.properties file has been provided");
        }
        System.setProperty("java.util.logging.config.file", runtimeDir.getLoggingProperties().getAbsolutePath());
        try (InputStream is = new FileInputStream(runtimeDir.getLoggingProperties())) {
            LogManager.getLogManager().readConfiguration(is);
            // go through all root handlers and set formatters based on properties
            Logger rootLogger = LogManager.getLogManager().getLogger("");
            for (Handler handler : rootLogger.getHandlers()) {
                String formatter = LogManager.getLogManager().getProperty(handler.getClass().getCanonicalName() + ".formatter");
                if (formatter != null) {
                    handler.setFormatter((Formatter) Class.forName(formatter).newInstance());
                }
            }
        } catch (SecurityException | IOException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
            LOGGER.log(Level.SEVERE, "Unable to reset the log manager", ex);
        }
    } else {
        // we are likely using our default properties file so see if we need to rewrite it
        if (logToFile) {
            // we need to reset our logging properties to use the file handler as well
            // read the default properties and then add the file handler properties
            Properties currentProps = new Properties();
            try (InputStream is = new FileInputStream(runtimeDir.getLoggingProperties())) {
                currentProps.load(is);
                // add file handler properties
                currentProps.setProperty("java.util.logging.FileHandler.pattern", userLogFile);
                currentProps.setProperty("handlers", "java.util.logging.FileHandler, java.util.logging.ConsoleHandler");
                currentProps.setProperty("java.util.logging.FileHandler.limit", "1024000");
                currentProps.setProperty("java.util.logging.FileHandler.count", "10");
                currentProps.setProperty("java.util.logging.FileHandler.level", "INFO");
                currentProps.setProperty("java.util.logging.FileHandler.formatter", "java.util.logging.SimpleFormatter");
                currentProps.setProperty("java.util.logging.FileHandler.append", "true");
            } catch (IOException ex) {
                LOGGER.log(Level.SEVERE, "Unable to load the logging properties from the runtime directory", ex);
            }
            // now write them back
            try (OutputStream os = new FileOutputStream(runtimeDir.getLoggingProperties())) {
                new SortedLoggingProperties(currentProps).store(os, "Generated Logging properties file from Payara Micro log to file option");
            } catch (IOException ex) {
                LOGGER.log(Level.SEVERE, "Unable to load the logging properties from the runtime directory", ex);
            }
        }
        System.setProperty("java.util.logging.config.file", runtimeDir.getLoggingProperties().getAbsolutePath());
        try (InputStream is = new FileInputStream(runtimeDir.getLoggingProperties())) {
            LogManager.getLogManager().readConfiguration(is);
            // reset the formatters on the two handlers
            // Logger rootLogger = Logger.getLogger("");
            String formatter = LogManager.getLogManager().getProperty("java.util.logging.ConsoleHandler.formatter");
            Formatter formatterClass = new ODLLogFormatter(null);
            try {
                formatterClass = (Formatter) Class.forName(formatter).newInstance();
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
                LOGGER.log(Level.SEVERE, "Specified Formatter class could not be loaded " + formatter, ex);
            }
            Logger rootLogger = Logger.getLogger("");
            for (Handler handler : rootLogger.getHandlers()) {
                handler.setFormatter(formatterClass);
            }
        } catch (SecurityException | IOException ex) {
            LOGGER.log(Level.SEVERE, "Unable to reset the log manager", ex);
        }
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Formatter(java.util.logging.Formatter) ODLLogFormatter(com.sun.enterprise.server.logging.ODLLogFormatter) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Handler(java.util.logging.Handler) SortedLoggingProperties(com.sun.common.util.logging.SortedLoggingProperties) IOException(java.io.IOException) Logger(java.util.logging.Logger) SortedLoggingProperties(com.sun.common.util.logging.SortedLoggingProperties) BootstrapProperties(org.glassfish.embeddable.BootstrapProperties) GlassFishProperties(org.glassfish.embeddable.GlassFishProperties) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) FileOutputStream(java.io.FileOutputStream) ODLLogFormatter(com.sun.enterprise.server.logging.ODLLogFormatter) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 48 with Formatter

use of java.util.logging.Formatter in project elastic-core-maven by OrdinaryDude.

the class MemoryHandler method getMessages.

/**
 * Return the log messages from the ring buffer
 *
 * @param   msgCount            Number of messages to return
 * @return                      List of log messages
 */
public List<String> getMessages(int msgCount) {
    List<String> rtnList = new ArrayList<>(buffer.length);
    synchronized (buffer) {
        int rtnSize = Math.min(msgCount, count);
        int pos = (start + (count - rtnSize)) % buffer.length;
        Formatter formatter = getFormatter();
        for (int i = 0; i < rtnSize; i++) {
            rtnList.add(formatter.format(buffer[pos++]));
            if (pos == buffer.length)
                pos = 0;
        }
    }
    return rtnList;
}
Also used : Formatter(java.util.logging.Formatter) ArrayList(java.util.ArrayList)

Example 49 with Formatter

use of java.util.logging.Formatter in project irontest by zheng-wang.

the class UpgradeActions method upgrade.

protected void upgrade(DefaultArtifactVersion systemDatabaseVersion, DefaultArtifactVersion jarFileVersion, String ironTestHome, String fullyQualifiedSystemDBURL, String user, String password) throws Exception {
    Formatter logFormatter = new LogFormatter();
    // set formatter for console logging
    LOGGER.getParent().getHandlers()[0].setFormatter(logFormatter);
    LOGGER.info("Upgrading Iron Test from v" + systemDatabaseVersion + " to v" + jarFileVersion + ".");
    // set up temp upgrade directory
    Path upgradeWorkspace = Files.createTempDirectory("irontest-upgrade-");
    Path logFilePath = Paths.get(upgradeWorkspace.toString(), "upgrade-from-v" + systemDatabaseVersion + "-to-v" + jarFileVersion + ".log");
    FileHandler logFileHandler = new FileHandler(logFilePath.toString());
    logFileHandler.setFormatter(logFormatter);
    LOGGER.addHandler(logFileHandler);
    LOGGER.info("Created temp upgrade directory " + upgradeWorkspace.toString());
    Path oldFolderInTempUpgradeDir = Paths.get(upgradeWorkspace.toString(), "old");
    Path newFolderInTempUpgradeDir = Paths.get(upgradeWorkspace.toString(), "new");
    Files.createDirectory(oldFolderInTempUpgradeDir);
    Files.createDirectory(newFolderInTempUpgradeDir);
    // system DB upgrade includes schema change and/or data migration
    boolean needsSystemDBUpgrade = upgradeSystemDBInTempDirIfNeeded(systemDatabaseVersion, jarFileVersion, ironTestHome, fullyQualifiedSystemDBURL, user, password, oldFolderInTempUpgradeDir, newFolderInTempUpgradeDir);
    boolean clearBrowserCacheNeeded = clearBrowserCacheIfNeeded(systemDatabaseVersion, jarFileVersion);
    // ------------------------- below steps will modify files in <IronTest_Home> -------------------------
    copyFilesToBeUpgraded(ironTestHome, systemDatabaseVersion, jarFileVersion);
    deleteOldJarsFromIronTestHome(ironTestHome);
    copyNewJarFromDistToIronTestHome(jarFileVersion, ironTestHome);
    // request user to execute pre system database change (upgrade, or simply version update) general manual upgrades if needed
    preSystemDBChangeGeneralManualUpgrades(systemDatabaseVersion, jarFileVersion);
    if (needsSystemDBUpgrade) {
        // copy files from the temp 'new' folder to <IronTest_Home>
        String systemDBFileName = getSystemDBFileName(fullyQualifiedSystemDBURL);
        Path ironTestHomeSystemDatabaseFolder = Paths.get(ironTestHome, "database");
        Path sourceFilePath = Paths.get(newFolderInTempUpgradeDir.toString(), "database", systemDBFileName);
        Path targetFilePath = Paths.get(ironTestHomeSystemDatabaseFolder.toString(), systemDBFileName);
        Files.copy(sourceFilePath, targetFilePath, StandardCopyOption.REPLACE_EXISTING);
        LOGGER.info("Copied " + sourceFilePath + " to " + targetFilePath + ".");
    } else {
        // only update version of system database under <IronTest_Home>
        Jdbi jdbi = Jdbi.create(fullyQualifiedSystemDBURL, user, password);
        updateVersionTableInSystemDatabase(jdbi, fullyQualifiedSystemDBURL, jarFileVersion);
    }
    String lineDelimiter = "------------------------------------------------------------------------";
    LOGGER.info(lineDelimiter);
    LOGGER.info("UPGRADE SUCCESS");
    LOGGER.info(lineDelimiter);
    LOGGER.info("You can start Iron Test now.");
    if (clearBrowserCacheNeeded) {
        LOGGER.info("If Iron Test page is already open, refresh the page (no need to restart browser).");
    }
    LOGGER.info(lineDelimiter);
    LOGGER.info("Refer to " + logFilePath + " for upgrade logs.");
}
Also used : Jdbi(org.jdbi.v3.core.Jdbi) Formatter(java.util.logging.Formatter) FileHandler(java.util.logging.FileHandler)

Example 50 with Formatter

use of java.util.logging.Formatter in project qpid-broker-j by apache.

the class Slf4jLoggingHandler method publish.

@Override
public void publish(final LogRecord record) {
    MappedLevel level = convertLevel(record);
    final Logger logger = getLogger(record.getLoggerName());
    if (level.isEnabled(logger)) {
        Formatter formatter = getFormatter();
        try {
            String message = formatter.format(record);
            try {
                level.log(logger, message);
            } catch (RuntimeException e) {
                reportError(null, e, ErrorManager.WRITE_FAILURE);
            }
        } catch (RuntimeException e) {
            reportError(null, e, ErrorManager.FORMAT_FAILURE);
        }
    }
}
Also used : Formatter(java.util.logging.Formatter) Logger(org.slf4j.Logger)

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