Search in sources :

Example 26 with Formatter

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

the class PayaraMicroImpl method resetLogging.

private void resetLogging() {
    String loggingProperty = System.getProperty("java.util.logging.config.file");
    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())) {
                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();
            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) IOException(java.io.IOException) Logger(java.util.logging.Logger) 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 27 with Formatter

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

the class GFFileHandler method postConstruct.

@Override
public void postConstruct() {
    String filename = evaluateFileName();
    File logFile = new File(filename);
    absoluteServerLogName = filename;
    if (!logFile.isAbsolute()) {
        logFile = new File(env.getDomainRoot(), filename);
        absoluteServerLogName = env.getDomainRoot() + File.separator + filename;
    }
    changeFileName(logFile);
    // Reading just few lines of log file to get the log fomatter used.
    BufferedReader br = null;
    String strLine = "";
    int odlFormatter = 0;
    int uniformLogFormatter = 0;
    int otherFormatter = 0;
    boolean mustRotate = false;
    String propValue = null;
    propValue = manager.getProperty(cname + ".logtoFile");
    boolean logToFile = false;
    if (propValue != null) {
        logToFile = Boolean.parseBoolean(propValue);
    }
    if (logToFile) {
        try {
            br = new BufferedReader(new FileReader(logFile));
            while ((strLine = br.readLine()) != null) {
                strLine = strLine.trim();
                if (!strLine.equals("")) {
                    if (LogFormatHelper.isUniformFormatLogHeader(strLine)) {
                        // for ufl formatter
                        uniformLogFormatter++;
                    } else if (LogFormatHelper.isODLFormatLogHeader(strLine)) {
                        // for ODL formatter
                        odlFormatter++;
                    } else {
                        // for other formatter
                        otherFormatter++;
                    }
                    // Rotate on startup for custom log files
                    if (otherFormatter > 0) {
                        mustRotate = true;
                    }
                    // Read only first log record line and break out of the loop
                    break;
                }
            }
        } catch (Exception e) {
            ErrorManager em = getErrorManager();
            if (em != null) {
                em.error(e.getMessage(), e, ErrorManager.GENERIC_FAILURE);
            }
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                }
            }
        }
        if (odlFormatter > 0) {
            currentgffileHandlerFormatter = "com.sun.enterprise.server.logging.ODLLogFormatter";
        } else if (uniformLogFormatter > 0) {
            currentgffileHandlerFormatter = "com.sun.enterprise.server.logging.UniformLogFormatter";
        }
        // start the Queue consumer thread.
        initializePump();
        LogRecord lr = new LogRecord(Level.INFO, LogFacade.GF_VERSION_INFO);
        lr.setParameters(new Object[] { Version.getFullVersion() });
        lr.setResourceBundle(ResourceBundle.getBundle(LogFacade.LOGGING_RB_NAME));
        lr.setThreadID((int) Thread.currentThread().getId());
        lr.setLoggerName(LogFacade.LOGGING_LOGGER_NAME);
        EarlyLogHandler.earlyMessages.add(lr);
        propValue = manager.getProperty(cname + ".rotationOnDateChange");
        boolean rotationOnDateChange = false;
        if (propValue != null) {
            rotationOnDateChange = Boolean.parseBoolean(propValue);
        }
        if (rotationOnDateChange) {
            dayBasedFileRotation = true;
            Long rotationTimeLimitValue = 0L;
            int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
            long systime = System.currentTimeMillis();
            String nextDate = dateFormat.format(date.getTime() + MILLIS_IN_DAY);
            Date nextDay = null;
            try {
                nextDay = dateFormat.parse(nextDate);
            } catch (ParseException e) {
                nextDay = new Date();
                lr = new LogRecord(Level.WARNING, LogFacade.DATE_PARSING_FAILED);
                lr.setParameters(new Object[] { nextDate });
                lr.setResourceBundle(ResourceBundle.getBundle(LogFacade.LOGGING_RB_NAME));
                lr.setThreadID((int) Thread.currentThread().getId());
                lr.setLoggerName(LogFacade.LOGGING_LOGGER_NAME);
                EarlyLogHandler.earlyMessages.add(lr);
            }
            long nextsystime = nextDay.getTime();
            rotationTimeLimitValue = nextsystime - systime;
            Task rotationTask = new Task() {

                @Override
                public Object run() {
                    rotate();
                    return null;
                }
            };
            if (cname.equals(GF_FILE_HANDER)) {
                LogRotationTimer.getInstance().startTimer(new LogRotationTimerTask(rotationTask, rotationTimeLimitValue / 60000));
            } else {
                PayaraNotificationLogRotationTimer.getInstance().startTimer(new LogRotationTimerTask(rotationTask, rotationTimeLimitValue / 60000));
            }
        } else {
            Long rotationTimeLimitValue = 0L;
            try {
                propValue = manager.getProperty(cname + ".rotationTimelimitInMinutes");
                if (propValue != null) {
                    rotationTimeLimitValue = Long.parseLong(propValue);
                }
            } catch (NumberFormatException e) {
                lr = new LogRecord(Level.WARNING, LogFacade.INVALID_ATTRIBUTE_VALUE);
                lr.setParameters(new Object[] { propValue, "rotationTimelimitInMinutes" });
                lr.setResourceBundle(ResourceBundle.getBundle(LogFacade.LOGGING_RB_NAME));
                lr.setThreadID((int) Thread.currentThread().getId());
                lr.setLoggerName(LogFacade.LOGGING_LOGGER_NAME);
                EarlyLogHandler.earlyMessages.add(lr);
            }
            if (rotationTimeLimitValue > 0) {
                Task rotationTask = new Task() {

                    public Object run() {
                        rotate();
                        return null;
                    }
                };
                if (cname.equals(GF_FILE_HANDER)) {
                    LogRotationTimer.getInstance().startTimer(new LogRotationTimerTask(rotationTask, rotationTimeLimitValue));
                } else {
                    PayaraNotificationLogRotationTimer.getInstance().startTimer(new LogRotationTimerTask(rotationTask, rotationTimeLimitValue));
                }
            }
        }
        // Also honor the size based rotation if configured.
        Integer rotationLimitAttrValue = DEFAULT_ROTATION_LIMIT_BYTES;
        try {
            propValue = manager.getProperty(cname + ".rotationLimitInBytes");
            if (propValue != null) {
                rotationLimitAttrValue = Integer.parseInt(propValue);
            }
        } catch (NumberFormatException e) {
            lr = new LogRecord(Level.WARNING, LogFacade.INVALID_ATTRIBUTE_VALUE);
            lr.setParameters(new Object[] { propValue, "rotationLimitInBytes" });
            lr.setResourceBundle(ResourceBundle.getBundle(LogFacade.LOGGING_RB_NAME));
            lr.setThreadID((int) Thread.currentThread().getId());
            lr.setLoggerName(LogFacade.LOGGING_LOGGER_NAME);
            EarlyLogHandler.earlyMessages.add(lr);
        }
        // it will be rotated.
        if (rotationLimitAttrValue >= MINIMUM_ROTATION_LIMIT_VALUE || rotationLimitAttrValue == DISABLE_LOG_FILE_ROTATION_VALUE) {
            setLimitForRotation(rotationLimitAttrValue);
        }
        // setLevel(Level.ALL);
        propValue = manager.getProperty(cname + ".flushFrequency");
        if (propValue != null) {
            try {
                flushFrequency = Integer.parseInt(propValue);
            } catch (NumberFormatException e) {
                lr = new LogRecord(Level.WARNING, LogFacade.INVALID_ATTRIBUTE_VALUE);
                lr.setParameters(new Object[] { propValue, "flushFrequency" });
                lr.setResourceBundle(ResourceBundle.getBundle(LogFacade.LOGGING_RB_NAME));
                lr.setThreadID((int) Thread.currentThread().getId());
                lr.setLoggerName(LogFacade.LOGGING_LOGGER_NAME);
                EarlyLogHandler.earlyMessages.add(lr);
            }
        }
        if (flushFrequency <= 0) {
            flushFrequency = 1;
        }
        propValue = manager.getProperty(cname + ".maxHistoryFiles");
        try {
            if (propValue != null) {
                maxHistoryFiles = Integer.parseInt(propValue);
            }
        } catch (NumberFormatException e) {
            lr = new LogRecord(Level.WARNING, LogFacade.INVALID_ATTRIBUTE_VALUE);
            lr.setParameters(new Object[] { propValue, "maxHistoryFiles" });
            lr.setResourceBundle(ResourceBundle.getBundle(LogFacade.LOGGING_RB_NAME));
            lr.setThreadID((int) Thread.currentThread().getId());
            lr.setLoggerName(LogFacade.LOGGING_LOGGER_NAME);
            EarlyLogHandler.earlyMessages.add(lr);
        }
        if (maxHistoryFiles < 0) {
            maxHistoryFiles = 10;
        }
        propValue = manager.getProperty(cname + ".compressOnRotation");
        boolean compressionOnRotation = false;
        if (propValue != null) {
            compressionOnRotation = Boolean.parseBoolean(propValue);
        }
        if (compressionOnRotation) {
            compressLogs = true;
        }
        String formatterName = manager.getProperty(cname + ".formatter");
        formatterName = (formatterName == null) ? DEFAULT_LOG_FILE_FORMATTER_CLASS_NAME : formatterName;
        // Below snapshot of the code is used to rotate server.log file on startup. It is used to avoid different format
        // log messages logged under same server.log file.
        gffileHandlerFormatter = formatterName;
        if (mustRotate) {
            rotate();
        } else if (gffileHandlerFormatter != null && !gffileHandlerFormatter.equals(currentgffileHandlerFormatter)) {
            rotate();
        }
        String excludeFields = manager.getProperty(LogManagerService.EXCLUDE_FIELDS_PROPERTY);
        boolean multiLineMode = Boolean.parseBoolean(manager.getProperty(LogManagerService.MULTI_LINE_MODE_PROPERTY));
        if (UniformLogFormatter.class.getName().equals(formatterName)) {
            configureUniformLogFormatter(excludeFields, multiLineMode);
        } else if (ODLLogFormatter.class.getName().equals(formatterName)) {
            configureODLFormatter(excludeFields, multiLineMode);
        } else if (JSONLogFormatter.class.getName().equals(formatterName)) {
            configureJSONFormatter(excludeFields, multiLineMode);
        } else {
            // Custom formatter is configured in logging.properties
            // Check if the user specified formatter is in play else
            // log an error message
            Formatter currentFormatter = this.getFormatter();
            if (currentFormatter == null || !currentFormatter.getClass().getName().equals(formatterName)) {
                Formatter formatter = findFormatterService(formatterName);
                if (formatter == null) {
                    lr = new LogRecord(Level.SEVERE, LogFacade.INVALID_FORMATTER_CLASS_NAME);
                    lr.setParameters(new Object[] { formatterName });
                    lr.setThreadID((int) Thread.currentThread().getId());
                    lr.setResourceBundle(ResourceBundle.getBundle(LogFacade.LOGGING_RB_NAME));
                    lr.setLoggerName(LogFacade.LOGGING_LOGGER_NAME);
                    EarlyLogHandler.earlyMessages.add(lr);
                    // Fall back to the GlassFish default
                    configureDefaultFormatter(excludeFields, multiLineMode);
                } else {
                    setFormatter(formatter);
                }
            }
        }
        formatterName = this.getFormatter().getClass().getName();
        lr = new LogRecord(Level.INFO, LogFacade.LOG_FORMATTER_INFO);
        lr.setParameters(new Object[] { formatterName });
        lr.setResourceBundle(ResourceBundle.getBundle(LogFacade.LOGGING_RB_NAME));
        lr.setThreadID((int) Thread.currentThread().getId());
        lr.setLoggerName(LogFacade.LOGGING_LOGGER_NAME);
        EarlyLogHandler.earlyMessages.add(lr);
    }
}
Also used : Task(org.glassfish.api.logging.Task) ErrorManager(java.util.logging.ErrorManager) JSONLogFormatter(fish.payara.enterprise.server.logging.JSONLogFormatter) Formatter(java.util.logging.Formatter) JSONLogFormatter(fish.payara.enterprise.server.logging.JSONLogFormatter) ParseException(java.text.ParseException) IOException(java.io.IOException) Date(java.util.Date) LogRecord(java.util.logging.LogRecord) GFLogRecord(com.sun.common.util.logging.GFLogRecord) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) ParseException(java.text.ParseException) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Example 28 with Formatter

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

the class LogManagerService method postConstruct.

/**
 * Initialize the loggers
 */
@Override
public void postConstruct() {
    // if the system property is already set, we don't need to do anything
    if (System.getProperty("java.util.logging.config.file") != null) {
        System.out.println("\n\n\n#!## LogManagerService.postConstruct : java.util.logging.config.file=" + System.getProperty("java.util.logging.config.file"));
        return;
    }
    // logging.properties massaging.
    final LogManager logMgr = LogManager.getLogManager();
    File logging = null;
    // reset settings
    try {
        logging = getLoggingFile();
        System.setProperty("java.util.logging.config.file", logging.getAbsolutePath());
        String rootFolder = env.getProps().get(com.sun.enterprise.util.SystemPropertyConstants.INSTALL_ROOT_PROPERTY);
        String templateDir = rootFolder + File.separator + "lib" + File.separator + "templates";
        File src = new File(templateDir, ServerEnvironmentImpl.kLoggingPropertiesFileName);
        File dest = new File(env.getConfigDirPath(), ServerEnvironmentImpl.kLoggingPropertiesFileName);
        System.out.println("\n\n\n#!## LogManagerService.postConstruct : rootFolder=" + rootFolder);
        System.out.println("#!## LogManagerService.postConstruct : templateDir=" + templateDir);
        System.out.println("#!## LogManagerService.postConstruct : src=" + src);
        System.out.println("#!## LogManagerService.postConstruct : dest=" + dest);
        if (!logging.exists()) {
            LOGGER.log(Level.FINE, "{0} not found, creating new file from template.", logging.getAbsolutePath());
            FileUtils.copy(src, dest);
            logging = new File(env.getConfigDirPath(), ServerEnvironmentImpl.kLoggingPropertiesFileName);
        }
        logMgr.readConfiguration();
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, LogFacade.ERROR_READING_CONF_FILE, e);
    }
    FormatterDelegate agentDelegate = null;
    if (agent != null) {
        agentDelegate = new AgentFormatterDelegate(agent);
    }
    // force the ConsoleHandler to use GF formatter
    String formatterClassName = null;
    try {
        Map<String, String> props = getLoggingProperties();
        formatterClassName = props.get(CONSOLEHANDLER_FORMATTER_PROPERTY);
        if (formatterClassName == null || formatterClassName.isEmpty()) {
            formatterClassName = UniformLogFormatter.class.getName();
        }
        consoleHandlerFormatterDetail = formatterClassName;
        excludeFields = props.get(EXCLUDE_FIELDS_PROPERTY);
        multiLineMode = Boolean.parseBoolean(props.get(MULTI_LINE_MODE_PROPERTY));
        if (formatterClassName.equals(UniformLogFormatter.class.getName())) {
            // used to support UFL formatter in GF.
            UniformLogFormatter formatter = new UniformLogFormatter();
            String cname = "com.sun.enterprise.server.logging.GFFileHandler";
            recordBeginMarker = props.get(cname + ".logFormatBeginMarker");
            if (recordBeginMarker == null || ("").equals(recordBeginMarker)) {
                LOGGER.log(Level.FINE, "Record begin marker is not a proper value so using default.");
                recordBeginMarker = RECORD_BEGIN_MARKER;
            }
            recordEndMarker = props.get(cname + ".logFormatEndMarker");
            if (recordEndMarker == null || ("").equals(recordEndMarker)) {
                LOGGER.log(Level.FINE, "Record end marker is not a proper value so using default.");
                recordEndMarker = RECORD_END_MARKER;
            }
            recordFieldSeparator = props.get(cname + ".logFormatFieldSeparator");
            if (recordFieldSeparator == null || ("").equals(recordFieldSeparator) || recordFieldSeparator.length() > 1) {
                LOGGER.log(Level.FINE, "Log Format field separator is not a proper value so using default.");
                recordFieldSeparator = RECORD_FIELD_SEPARATOR;
            }
            recordDateFormat = props.get(cname + ".logFormatDateFormat");
            if (recordDateFormat != null && !("").equals(recordDateFormat)) {
                SimpleDateFormat sdf = new SimpleDateFormat(recordDateFormat);
                try {
                    sdf.format(new Date());
                } catch (Exception e) {
                    LOGGER.log(Level.FINE, "Date Format specified is wrong so using default.");
                    recordDateFormat = RECORD_DATE_FORMAT;
                }
            } else {
                LOGGER.log(Level.FINE, "Date Format specified is wrong so using default.");
                recordDateFormat = RECORD_DATE_FORMAT;
            }
            formatter.setRecordBeginMarker(recordBeginMarker);
            formatter.setRecordEndMarker(recordEndMarker);
            formatter.setRecordDateFormat(recordDateFormat);
            formatter.setRecordFieldSeparator(recordFieldSeparator);
            formatter.setExcludeFields(excludeFields);
            formatter.setMultiLineMode(multiLineMode);
            for (Handler handler : logMgr.getLogger("").getHandlers()) {
                // only get the ConsoleHandler
                if (handler.getClass().equals(ConsoleHandler.class)) {
                    handler.setFormatter(formatter);
                    break;
                }
            }
        } else if (formatterClassName.equals(ODLLogFormatter.class.getName())) {
            // used to support ODL formatter in GF.
            ODLLogFormatter formatter = new ODLLogFormatter();
            formatter.setExcludeFields(excludeFields);
            formatter.setMultiLineMode(multiLineMode);
            for (Handler handler : logMgr.getLogger("").getHandlers()) {
                // only get the ConsoleHandler
                if (handler.getClass().equals(ConsoleHandler.class)) {
                    handler.setFormatter(formatter);
                    break;
                }
            }
        } else if (formatterClassName.equals(JSONLogFormatter.class.getName())) {
            JSONLogFormatter formatter = new JSONLogFormatter();
            formatter.setExcludeFields(excludeFields);
            for (Handler handler : logMgr.getLogger("").getHandlers()) {
                // only get the ConsoleHandler
                if (handler.getClass().equals(ConsoleHandler.class)) {
                    handler.setFormatter(formatter);
                    break;
                }
            }
        }
        // setting default attributes value for all properties
        serverLogFileDetail = props.get(SERVER_LOG_FILE_PROPERTY);
        handlerDetail = props.get(HANDLER_PROPERTY);
        handlerServices = props.get(HANDLER_SERVICES_PROPERTY);
        if (handlerServices == null) {
            handlerServices = "";
        }
        consoleHandlerFormatterDetail = props.get(CONSOLEHANDLER_FORMATTER_PROPERTY);
        gffileHandlerFormatterDetail = props.get(GFFILEHANDLER_FORMATTER_PROPERTY);
        rotationOnTimeLimitInMinutesDetail = props.get(ROTATIONTIMELIMITINMINUTES_PROPERTY);
        flushFrequencyDetail = props.get(FLUSHFREQUENCY_PROPERTY);
        filterHandlerDetails = props.get(FILEHANDLER_LIMIT_PROPERTY);
        logToFileDetail = props.get(LOGTOFILE_PROPERTY);
        logToConsoleDetail = props.get(LOGTOCONSOLE_PROPERTY);
        rotationInTimeLimitInBytesDetail = props.get(ROTATIONLIMITINBYTES_PROPERTY);
        useSystemLoggingDetail = props.get(USESYSTEMLOGGING_PROPERTY);
        fileHandlerCountDetail = props.get(FILEHANDLER_COUNT_PROPERTY);
        retainErrorsStaticticsDetail = props.get(RETAINERRORSSTATICTICS_PROPERTY);
        log4jVersionDetail = props.get(LOG4J_VERSION_PROPERTY);
        maxHistoryFilesDetail = props.get(MAXHISTORY_FILES_PROPERTY);
        rotationOnDateChangeDetail = props.get(ROTATIONONDATECHANGE_PROPERTY);
        fileHandlerPatternDetail = props.get(FILEHANDLER_PATTERN_PROPERTY);
        fileHandlerFormatterDetail = props.get(FILEHANDLER_FORMATTER_PROPERTY);
        logFormatDateFormatDetail = props.get(LOGFORMAT_DATEFORMAT_PROPERTY);
        compressOnRotationDetail = props.get(COMPRESS_ON_ROTATION_PROPERTY);
        // Payara Notification Logging
        payaraNotificationLogFileDetail = props.get(PAYARA_NOTIFICATION_LOG_FILE_PROPERTY);
        payaraNotificationlogToFileDetail = props.get(PAYARA_NOTIFICATION_LOGTOFILE_PROPERTY);
        payaraNotificationLogRotationOnDateChangeDetail = props.get(PAYARA_NOTIFICATION_LOG_ROTATIONONDATECHANGE_PROPERTY);
        payaraNotificationLogRotationOnTimeLimitInMinutesDetail = props.get(PAYARA_NOTIFICATION_LOG_ROTATIONTIMELIMITINMINUTES_PROPERTY);
        payaraNotificationLogRotationInTimeLimitInBytesDetail = props.get(PAYARA_NOTIFICATION_LOG_ROTATIONLIMITINBYTES_PROPERTY);
        payaraNotificationLogmaxHistoryFilesDetail = props.get(PAYARA_NOTIFICATION_LOG_MAXHISTORY_FILES_PROPERTY);
        payaraNotificationLogCompressOnRotationDetail = props.get(PAYARA_NOTIFICATION_LOG_COMPRESS_ON_ROTATION_PROPERTY);
        payaraJsonUnderscorePrefix = props.get(PAYARA_JSONLOGFORMATTER_UNDERSCORE);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, LogFacade.ERROR_APPLYING_CONF, e);
    }
    Collection<Handler> handlers = getHandlerServices();
    if (handlers != null && handlers.size() > 0) {
        // add the new handlers to the root logger
        for (Handler handler : handlers) {
            addHandler(handler);
        }
    }
    // Logger.getLogger() is still synchronized.
    synchronized (java.util.logging.Logger.class) {
        synchronized (logMgr) {
            Enumeration<String> loggerNames = logMgr.getLoggerNames();
            while (loggerNames.hasMoreElements()) {
                String loggerName = loggerNames.nextElement();
                Logger logger = logMgr.getLogger(loggerName);
                if (logger == null) {
                    continue;
                }
                for (Handler handler : logger.getHandlers()) {
                    Formatter formatter = handler.getFormatter();
                    if (formatter != null && formatter instanceof UniformLogFormatter) {
                        ((UniformLogFormatter) formatter).setDelegate(agentDelegate);
                    }
                }
            }
        }
    }
    // add the filter if there is one
    try {
        Map<String, String> map = getLoggingProperties();
        String filterClassName = map.get(LoggingXMLNames.xmltoPropsMap.get("log-filter"));
        if (filterClassName != null) {
            Filter filterClass = habitat.getService(Filter.class, filterClassName);
            Logger rootLogger = Logger.getLogger("");
            if (rootLogger != null) {
                rootLogger.setFilter(filterClass);
            }
        }
    } catch (java.io.IOException ex) {
    }
    // redirect stderr and stdout, a better way to do this
    // http://blogs.sun.com/nickstephen/entry/java_redirecting_system_out_and
    Logger _ologger = LogFacade.STDOUT_LOGGER;
    stdoutOutputStream = new LoggingOutputStream(_ologger, Level.INFO);
    LoggingOutputStream.LoggingPrintStream pout = stdoutOutputStream.new LoggingPrintStream(stdoutOutputStream);
    System.setOut(pout);
    Logger _elogger = LogFacade.STDERR_LOGGER;
    stderrOutputStream = new LoggingOutputStream(_elogger, Level.SEVERE);
    LoggingOutputStream.LoggingPrintStream perr = stderrOutputStream.new LoggingPrintStream(stderrOutputStream);
    System.setErr(perr);
    // finally listen to changes to the logging.properties file
    if (logging != null) {
        fileMonitoring.monitors(logging, new FileMonitoring.FileChangeListener() {

            @Override
            public void changed(File changedFile) {
                synchronized (gfHandlers) {
                    try {
                        Map<String, String> props = getLoggingProperties();
                        loggerReference = new Vector<Logger>();
                        if (props == null)
                            return;
                        // Set<String> keys = props.keySet();
                        for (Map.Entry<String, String> entry : props.entrySet()) {
                            String a = entry.getKey();
                            String val = entry.getValue();
                            if (a.endsWith(".level")) {
                                String n = a.substring(0, a.lastIndexOf(".level"));
                                Level l = Level.parse(val);
                                if (gfHandlers.containsKey(n)) {
                                    // check if this is one of our handlers
                                    Handler h = (Handler) gfHandlers.get(n);
                                    h.setLevel(l);
                                } else if (n.equals("java.util.logging.ConsoleHandler")) {
                                    Logger logger = Logger.getLogger("");
                                    Handler[] h = logger.getHandlers();
                                    for (int i = 0; i < h.length; i++) {
                                        String name = h[i].toString();
                                        if (name.contains("java.util.logging.ConsoleHandler"))
                                            h[i].setLevel(l);
                                    }
                                } else {
                                    // Assume it is a logger
                                    Logger appLogger = Logger.getLogger(n);
                                    appLogger.setLevel(l);
                                    loggerReference.add(appLogger);
                                }
                            } else if (a.equals(SERVER_LOG_FILE_PROPERTY)) {
                                // check if file name was changed and send notification
                                if (!val.equals(serverLogFileDetail)) {
                                    PropertyChangeEvent pce = new PropertyChangeEvent(this, a, serverLogFileDetail, val);
                                    UnprocessedChangeEvents ucel = new UnprocessedChangeEvents(new UnprocessedChangeEvent(pce, "server log filename changed."));
                                    List<UnprocessedChangeEvents> b = new ArrayList();
                                    b.add(ucel);
                                    ucl.unprocessedTransactedEvents(b);
                                }
                            } else if (a.equals(HANDLER_PROPERTY)) {
                                if (!val.equals(handlerDetail)) {
                                    generateAttributeChangeEvent(HANDLER_PROPERTY, handlerDetail, props);
                                }
                            } else if (a.equals(HANDLER_SERVICES_PROPERTY)) {
                                if (!val.equals(handlerServices)) {
                                    generateAttributeChangeEvent(HANDLER_SERVICES_PROPERTY, handlerServices, props);
                                }
                            } else if (a.equals(CONSOLEHANDLER_FORMATTER_PROPERTY)) {
                                if (!val.equals(consoleHandlerFormatterDetail)) {
                                    generateAttributeChangeEvent(CONSOLEHANDLER_FORMATTER_PROPERTY, consoleHandlerFormatterDetail, props);
                                }
                            } else if (a.equals(GFFILEHANDLER_FORMATTER_PROPERTY)) {
                                if (!val.equals(gffileHandlerFormatterDetail)) {
                                    generateAttributeChangeEvent(GFFILEHANDLER_FORMATTER_PROPERTY, gffileHandlerFormatterDetail, props);
                                }
                            } else if (a.equals(ROTATIONTIMELIMITINMINUTES_PROPERTY)) {
                                if (!val.equals(rotationOnTimeLimitInMinutesDetail)) {
                                    generateAttributeChangeEvent(ROTATIONTIMELIMITINMINUTES_PROPERTY, rotationOnTimeLimitInMinutesDetail, props);
                                }
                            } else if (a.equals(FLUSHFREQUENCY_PROPERTY)) {
                                if (!val.equals(flushFrequencyDetail)) {
                                    generateAttributeChangeEvent(FLUSHFREQUENCY_PROPERTY, flushFrequencyDetail, props);
                                }
                            } else if (a.equals(FILEHANDLER_LIMIT_PROPERTY)) {
                                if (!val.equals(filterHandlerDetails)) {
                                    generateAttributeChangeEvent(FILEHANDLER_LIMIT_PROPERTY, filterHandlerDetails, props);
                                }
                            } else if (a.equals(LOGTOFILE_PROPERTY)) {
                                if (!val.equals(logToFileDetail)) {
                                    generateAttributeChangeEvent(LOGTOFILE_PROPERTY, logToFileDetail, props);
                                }
                            } else if (a.equals(LOGTOCONSOLE_PROPERTY)) {
                                if (!val.equals(logToConsoleDetail)) {
                                    generateAttributeChangeEvent(LOGTOCONSOLE_PROPERTY, logToConsoleDetail, props);
                                }
                            } else if (a.equals(ROTATIONLIMITINBYTES_PROPERTY)) {
                                if (!val.equals(rotationInTimeLimitInBytesDetail)) {
                                    generateAttributeChangeEvent(ROTATIONLIMITINBYTES_PROPERTY, rotationInTimeLimitInBytesDetail, props);
                                }
                            } else if (a.equals(USESYSTEMLOGGING_PROPERTY)) {
                                if (!val.equals(useSystemLoggingDetail)) {
                                    generateAttributeChangeEvent(USESYSTEMLOGGING_PROPERTY, useSystemLoggingDetail, props);
                                }
                            } else if (a.equals(FILEHANDLER_COUNT_PROPERTY)) {
                                if (!val.equals(fileHandlerCountDetail)) {
                                    generateAttributeChangeEvent(FILEHANDLER_COUNT_PROPERTY, fileHandlerCountDetail, props);
                                }
                            } else if (a.equals(RETAINERRORSSTATICTICS_PROPERTY)) {
                                if (!val.equals(retainErrorsStaticticsDetail)) {
                                    generateAttributeChangeEvent(RETAINERRORSSTATICTICS_PROPERTY, retainErrorsStaticticsDetail, props);
                                }
                            } else if (a.equals(LOG4J_VERSION_PROPERTY)) {
                                if (!val.equals(log4jVersionDetail)) {
                                    generateAttributeChangeEvent(LOG4J_VERSION_PROPERTY, log4jVersionDetail, props);
                                }
                            } else if (a.equals(MAXHISTORY_FILES_PROPERTY)) {
                                if (!val.equals(maxHistoryFilesDetail)) {
                                    generateAttributeChangeEvent(MAXHISTORY_FILES_PROPERTY, maxHistoryFilesDetail, props);
                                }
                            } else if (a.equals(ROTATIONONDATECHANGE_PROPERTY)) {
                                if (!val.equals(rotationOnDateChangeDetail)) {
                                    generateAttributeChangeEvent(ROTATIONONDATECHANGE_PROPERTY, rotationOnDateChangeDetail, props);
                                }
                            } else if (a.equals(FILEHANDLER_PATTERN_PROPERTY)) {
                                if (!val.equals(fileHandlerPatternDetail)) {
                                    generateAttributeChangeEvent(FILEHANDLER_PATTERN_PROPERTY, fileHandlerPatternDetail, props);
                                }
                            } else if (a.equals(FILEHANDLER_FORMATTER_PROPERTY)) {
                                if (!val.equals(fileHandlerFormatterDetail)) {
                                    generateAttributeChangeEvent(FILEHANDLER_FORMATTER_PROPERTY, fileHandlerFormatterDetail, props);
                                }
                            } else if (a.equals(LOGFORMAT_DATEFORMAT_PROPERTY)) {
                                if (!val.equals(logFormatDateFormatDetail)) {
                                    generateAttributeChangeEvent(LOGFORMAT_DATEFORMAT_PROPERTY, logFormatDateFormatDetail, props);
                                }
                            } else if (a.equals(EXCLUDE_FIELDS_PROPERTY)) {
                                val = (val == null) ? "" : val;
                                excludeFields = (excludeFields == null) ? "" : excludeFields;
                                if (!val.equals(excludeFields)) {
                                    generateAttributeChangeEvent(EXCLUDE_FIELDS_PROPERTY, excludeFields, props);
                                }
                            } else if (a.equals(MULTI_LINE_MODE_PROPERTY)) {
                                String oldVal = Boolean.toString(multiLineMode);
                                if (!val.equalsIgnoreCase(oldVal)) {
                                    generateAttributeChangeEvent(MULTI_LINE_MODE_PROPERTY, oldVal, props);
                                }
                            } else if (a.equals(COMPRESS_ON_ROTATION_PROPERTY)) {
                                if (!val.equals(compressOnRotationDetail)) {
                                    generateAttributeChangeEvent(COMPRESS_ON_ROTATION_PROPERTY, compressOnRotationDetail, props);
                                }
                            } else if (a.equals(PAYARA_NOTIFICATION_LOG_FILE_PROPERTY)) {
                                if (!val.equals(payaraNotificationLogFileDetail)) {
                                    generateAttributeChangeEvent(PAYARA_NOTIFICATION_LOG_FILE_PROPERTY, payaraNotificationLogFileDetail, props);
                                }
                            } else if (a.equals(PAYARA_NOTIFICATION_LOGTOFILE_PROPERTY)) {
                                if (!val.equals(payaraNotificationlogToFileDetail)) {
                                    generateAttributeChangeEvent(PAYARA_NOTIFICATION_LOGTOFILE_PROPERTY, payaraNotificationlogToFileDetail, props);
                                }
                            } else if (a.equals(PAYARA_NOTIFICATION_LOG_ROTATIONTIMELIMITINMINUTES_PROPERTY)) {
                                if (!val.equals(payaraNotificationLogRotationOnTimeLimitInMinutesDetail)) {
                                    generateAttributeChangeEvent(PAYARA_NOTIFICATION_LOG_ROTATIONTIMELIMITINMINUTES_PROPERTY, payaraNotificationLogRotationOnTimeLimitInMinutesDetail, props);
                                }
                            } else if (a.equals(PAYARA_NOTIFICATION_LOG_ROTATIONLIMITINBYTES_PROPERTY)) {
                                if (!val.equals(payaraNotificationLogRotationInTimeLimitInBytesDetail)) {
                                    generateAttributeChangeEvent(PAYARA_NOTIFICATION_LOG_ROTATIONLIMITINBYTES_PROPERTY, payaraNotificationLogRotationInTimeLimitInBytesDetail, props);
                                }
                            } else if (a.equals(PAYARA_NOTIFICATION_LOG_MAXHISTORY_FILES_PROPERTY)) {
                                if (!val.equals(payaraNotificationLogmaxHistoryFilesDetail)) {
                                    generateAttributeChangeEvent(PAYARA_NOTIFICATION_LOG_MAXHISTORY_FILES_PROPERTY, payaraNotificationLogmaxHistoryFilesDetail, props);
                                }
                            } else if (a.equals(PAYARA_NOTIFICATION_LOG_COMPRESS_ON_ROTATION_PROPERTY)) {
                                if (!val.equals(payaraNotificationLogCompressOnRotationDetail)) {
                                    generateAttributeChangeEvent(PAYARA_NOTIFICATION_LOG_COMPRESS_ON_ROTATION_PROPERTY, payaraNotificationLogCompressOnRotationDetail, props);
                                }
                            }
                        }
                        LOGGER.log(Level.INFO, LogFacade.UPDATED_LOG_LEVELS);
                    } catch (Exception e) {
                        LOGGER.log(Level.SEVERE, LogFacade.ERROR_APPLYING_CONF, e);
                    }
                }
            }

            @Override
            public void deleted(File deletedFile) {
                LOGGER.log(Level.WARNING, LogFacade.CONF_FILE_DELETED, deletedFile.getAbsolutePath());
            }
        });
    }
    // Log the messages that were generated very early before this Service
    // started.  Just use our own logger...
    List<EarlyLogger.LevelAndMessage> catchUp = EarlyLogger.getEarlyMessages();
    if (!catchUp.isEmpty()) {
        for (EarlyLogger.LevelAndMessage levelAndMessage : catchUp) {
            LOGGER.log(levelAndMessage.getLevel(), levelAndMessage.getMessage());
        }
        catchUp.clear();
    }
    ArrayBlockingQueue<LogRecord> catchEarlyMessage = EarlyLogHandler.earlyMessages;
    while (!catchEarlyMessage.isEmpty()) {
        LogRecord logRecord = catchEarlyMessage.poll();
        if (logRecord != null) {
            LOGGER.log(logRecord);
        }
    }
}
Also used : UnprocessedChangeEvents(org.jvnet.hk2.config.UnprocessedChangeEvents) FileMonitoring(org.glassfish.api.admin.FileMonitoring) Formatter(java.util.logging.Formatter) JSONLogFormatter(fish.payara.enterprise.server.logging.JSONLogFormatter) EarlyLogger(com.sun.enterprise.util.EarlyLogger) EarlyLogger(com.sun.enterprise.util.EarlyLogger) PropertyChangeEvent(java.beans.PropertyChangeEvent) JSONLogFormatter(fish.payara.enterprise.server.logging.JSONLogFormatter) UnprocessedChangeEvent(org.jvnet.hk2.config.UnprocessedChangeEvent) LoggingOutputStream(com.sun.common.util.logging.LoggingOutputStream) PayaraNotificationFileHandler(fish.payara.enterprise.server.logging.PayaraNotificationFileHandler) EarlyLogHandler(com.sun.enterprise.module.bootstrap.EarlyLogHandler) IOException(java.io.IOException) IOException(java.io.IOException) AgentFormatterDelegate(com.sun.enterprise.v3.logging.AgentFormatterDelegate) IOException(java.io.IOException) AgentFormatterDelegate(com.sun.enterprise.v3.logging.AgentFormatterDelegate) java.util(java.util) RunLevel(org.glassfish.hk2.runlevel.RunLevel) InitRunLevel(org.glassfish.internal.api.InitRunLevel) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Example 29 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 30 with Formatter

use of java.util.logging.Formatter in project SilverKing by Morgan-Stanley.

the class TerminatorAsyncLogger method getLogger.

private Logger getLogger() throws FileNotFoundException {
    synchronized (this) {
        // not really needed yet, but TerminatorAsyncLogger is exposed to more than one thread
        if (log == null) {
            PrintStream ps = new PrintStream(new File(logFileName));
            log = Logger.getLogger(argusLoggerName);
            Formatter formatter = new HighTemporalResolutionFormatter();
            handler = new StreamHandler(ps, formatter);
            log.addHandler(handler);
            log.setLevel(Level.ALL);
        }
        return log;
    }
}
Also used : PrintStream(java.io.PrintStream) HighTemporalResolutionFormatter(com.ms.silverking.log.HighTemporalResolutionFormatter) HighTemporalResolutionFormatter(com.ms.silverking.log.HighTemporalResolutionFormatter) Formatter(java.util.logging.Formatter) StreamHandler(java.util.logging.StreamHandler) File(java.io.File)

Aggregations

Formatter (java.util.logging.Formatter)44 LogRecord (java.util.logging.LogRecord)18 File (java.io.File)13 SimpleFormatter (java.util.logging.SimpleFormatter)12 IOException (java.io.IOException)11 Logger (java.util.logging.Logger)11 FileHandler (java.util.logging.FileHandler)10 Handler (java.util.logging.Handler)9 Date (java.util.Date)6 Test (org.junit.Test)6 SimpleDateFormat (java.text.SimpleDateFormat)5 ConsoleHandler (java.util.logging.ConsoleHandler)5 Config (edu.neu.ccs.pyramid.configuration.Config)4 JSONLogFormatter (fish.payara.enterprise.server.logging.JSONLogFormatter)4 Level (java.util.logging.Level)4 StreamHandler (java.util.logging.StreamHandler)4 Pair (edu.neu.ccs.pyramid.util.Pair)3 DateFormat (java.text.DateFormat)3 ErrorManager (java.util.logging.ErrorManager)3 Filter (java.util.logging.Filter)3