diff --git a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployConsoleFormatter.java b/core/src/main/java/oracle/weblogic/deploy/logging/ConsoleFormatter.java similarity index 86% rename from core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployConsoleFormatter.java rename to core/src/main/java/oracle/weblogic/deploy/logging/ConsoleFormatter.java index f4a3c843d3..9a8ae054d1 100644 --- a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployConsoleFormatter.java +++ b/core/src/main/java/oracle/weblogic/deploy/logging/ConsoleFormatter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle Corporation and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2022, Oracle Corporation and/or its affiliates. * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ package oracle.weblogic.deploy.logging; @@ -13,7 +13,7 @@ * format the LogRecord into a localized String. To select a different formatter, inject * that instance into the set formatter of this Instance. */ -public class WLSDeployConsoleFormatter extends Formatter { +public class ConsoleFormatter extends Formatter { // Default Formatter if another is not injected private Formatter formatter = new WLSDeployLogFormatter(); @@ -23,10 +23,10 @@ public String format(LogRecord logRecord) { return formatter.format(cloned); } + @SuppressWarnings("unused") public void setFormatter(Formatter formatter) { if (formatter != null) { this.formatter = formatter; } } - -} \ No newline at end of file +} diff --git a/core/src/main/java/oracle/weblogic/deploy/logging/LoggingUtils.java b/core/src/main/java/oracle/weblogic/deploy/logging/LoggingUtils.java index 738fa86862..407ebbd20c 100644 --- a/core/src/main/java/oracle/weblogic/deploy/logging/LoggingUtils.java +++ b/core/src/main/java/oracle/weblogic/deploy/logging/LoggingUtils.java @@ -1,64 +1,39 @@ /* - * Copyright (c) 2019, 2020, Oracle Corporation and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2022, Oracle Corporation and/or its affiliates. * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ package oracle.weblogic.deploy.logging; -import java.text.MessageFormat; import java.util.Properties; -import java.util.logging.Handler; import java.util.logging.LogRecord; -import static oracle.weblogic.deploy.logging.WLSDeployLoggingConfig.ERROR_EXIT_CODE; - +/** + * Utility class with methods used by the logging framework. + */ public class LoggingUtils { - public static Class getHandlerClass(String handlerName) { - Class handler = null; - try { - Class checkClass = Class.forName(handlerName); - @SuppressWarnings("unchecked") - Class castHandler = (Class)checkClass.asSubclass(Class.forName(handlerName)); - handler = castHandler; - } catch(ClassNotFoundException | ClassCastException cnf) { - exitWithError( - MessageFormat.format("Unable to find handler class {0} so skipping logging configuration", - handlerName)); - } - return handler; - } - - public static T getHandlerInstance(Class handlerClass) { - T handler = null; - try { - handler = handlerClass.newInstance(); - } catch (InstantiationException | IllegalAccessException e){ - exitWithError(MessageFormat.format("Unable to instantiate Handler for Class {0}", handlerClass)); - } - return handler; - } - - public static T getHandlerInstance(String handlerClassName) { - return getHandlerInstance(LoggingUtils.getHandlerClass(handlerClassName)); - } - - public static void exitWithError(String message) { - System.err.println(message); - System.exit(ERROR_EXIT_CODE); + private LoggingUtils() { + // hide the constructor } - public static LogRecord cloneRecordWithoutException(LogRecord record) { - LogRecord newRecord = new LogRecord(record.getLevel(), record.getMessage()); - - newRecord.setLoggerName(record.getLoggerName()); - newRecord.setMillis(record.getMillis()); - newRecord.setParameters(record.getParameters()); - newRecord.setResourceBundle(record.getResourceBundle()); - newRecord.setResourceBundleName(record.getResourceBundleName()); - newRecord.setSequenceNumber(record.getSequenceNumber()); - newRecord.setSourceClassName(record.getSourceClassName()); - newRecord.setSourceMethodName(record.getSourceMethodName()); - newRecord.setThreadID(record.getThreadID()); + /** + * Make a copy of a log record without the exception. + * + * @param logRecord the log record to copy + * @return the cloned log record without the exception + */ + public static LogRecord cloneRecordWithoutException(LogRecord logRecord) { + LogRecord newRecord = new LogRecord(logRecord.getLevel(), logRecord.getMessage()); + + newRecord.setLoggerName(logRecord.getLoggerName()); + newRecord.setMillis(logRecord.getMillis()); + newRecord.setParameters(logRecord.getParameters()); + newRecord.setResourceBundle(logRecord.getResourceBundle()); + newRecord.setResourceBundleName(logRecord.getResourceBundleName()); + newRecord.setSequenceNumber(logRecord.getSequenceNumber()); + newRecord.setSourceClassName(logRecord.getSourceClassName()); + newRecord.setSourceMethodName(logRecord.getSourceMethodName()); + newRecord.setThreadID(logRecord.getThreadID()); // Skip thrown return newRecord; } @@ -70,5 +45,4 @@ public static void printLogProperties(Properties logProps, String prefix) { } } } - -} \ No newline at end of file +} diff --git a/core/src/main/java/oracle/weblogic/deploy/logging/PlatformLogger.java b/core/src/main/java/oracle/weblogic/deploy/logging/PlatformLogger.java index d9da6b011b..a8628bbf28 100644 --- a/core/src/main/java/oracle/weblogic/deploy/logging/PlatformLogger.java +++ b/core/src/main/java/oracle/weblogic/deploy/logging/PlatformLogger.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2019, Oracle Corporation and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2022, Oracle Corporation and/or its affiliates. * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ package oracle.weblogic.deploy.logging; @@ -341,6 +341,7 @@ public boolean isFinestEnabled() { * * @return whether or not the INFO level is enabled */ + @SuppressWarnings("unused") public boolean isInfoEnabled() { return logger.isLoggable(Level.INFO); } @@ -369,6 +370,7 @@ public boolean isSevereEnabled() { * * @return whether or not the WARNING level is enabled */ + @SuppressWarnings("unused") public boolean isWarningEnabled() { return logger.isLoggable(Level.WARNING); } @@ -535,6 +537,7 @@ public void warning(String msg, Throwable thrown) { * * @return List of Logger from the Log Manager */ + @SuppressWarnings("unused") public static List getLoggers() { LogManager manager = LogManager.getLogManager(); Enumeration e = manager.getLoggerNames(); @@ -577,18 +580,18 @@ CallerDetails inferCaller() { } private LogRecord getLogRecord(Level level, CallerDetails details, String msg, Throwable error, Object... params) { - LogRecord record = new LogRecord(level, msg); - record.setLoggerName(this.getName()); - record.setMillis(System.currentTimeMillis()); + LogRecord logRecord = new LogRecord(level, msg); + logRecord.setLoggerName(this.getName()); + logRecord.setMillis(System.currentTimeMillis()); if (params != null && params.length != 0) { - record.setParameters(params); + logRecord.setParameters(params); } - record.setResourceBundle(logger.getResourceBundle()); - record.setSourceClassName(details.clazz); - record.setSourceMethodName(details.method); - record.setThreadID((int)Thread.currentThread().getId()); - record.setThrown(error); - return record; + logRecord.setResourceBundle(logger.getResourceBundle()); + logRecord.setSourceClassName(details.clazz); + logRecord.setSourceMethodName(details.method); + logRecord.setThreadID((int)Thread.currentThread().getId()); + logRecord.setThrown(error); + return logRecord; } /** diff --git a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployConsoleErrorFilter.java b/core/src/main/java/oracle/weblogic/deploy/logging/StderrFilter.java similarity index 68% rename from core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployConsoleErrorFilter.java rename to core/src/main/java/oracle/weblogic/deploy/logging/StderrFilter.java index ac8e62a668..0e51dbd50e 100644 --- a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployConsoleErrorFilter.java +++ b/core/src/main/java/oracle/weblogic/deploy/logging/StderrFilter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle Corporation and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2022, Oracle Corporation and/or its affiliates. * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ package oracle.weblogic.deploy.logging; @@ -12,16 +12,15 @@ * This Class queries the information in the LogRecord to determine if it can be written to the OutputStream * associated with Error log record types. */ -public class WLSDeployConsoleErrorFilter implements Filter { - +@SuppressWarnings("unused") +public class StderrFilter implements Filter { @Override - public boolean isLoggable(LogRecord record) { + public boolean isLoggable(LogRecord logRecord) { boolean stdErr = false; - int level = record.getLevel() == null ? 0 : record.getLevel().intValue(); + int level = logRecord.getLevel() == null ? 0 : logRecord.getLevel().intValue(); if (level == Level.WARNING.intValue() || level == Level.SEVERE.intValue()) { stdErr = true; } return stdErr; } - -} \ No newline at end of file +} diff --git a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLoggingStderrHandler.java b/core/src/main/java/oracle/weblogic/deploy/logging/StderrHandler.java similarity index 50% rename from core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLoggingStderrHandler.java rename to core/src/main/java/oracle/weblogic/deploy/logging/StderrHandler.java index 4e223095de..c1b5885983 100644 --- a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLoggingStderrHandler.java +++ b/core/src/main/java/oracle/weblogic/deploy/logging/StderrHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle Corporation and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2022, Oracle Corporation and/or its affiliates. * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ package oracle.weblogic.deploy.logging; @@ -8,22 +8,19 @@ import java.util.logging.StreamHandler; /** - * This Class extends the StreamHandler to write log records to STDERR. The "wlsdeploy" Logger - * is configured with an instance of this Handler class and an instance of Class @WLSDeployStdoutHandler@ - * to log records to the STDOUT and STDERR output streams. - *

- * Attach a logger or filter to this Handler to direct log records to the STDERR output stream + * This Class extends the StreamHandler to write log records to STDERR. */ -public class WLSDeployLoggingStderrHandler extends StreamHandler { +@SuppressWarnings("unused") +public class StderrHandler extends StreamHandler { - public WLSDeployLoggingStderrHandler() { + public StderrHandler() { super(); setOutputStream(System.err); } @Override - public void publish(LogRecord record) { - super.publish(record); + public synchronized void publish(LogRecord logRecord) { + super.publish(logRecord); flush(); } @@ -33,8 +30,7 @@ public void publish(LogRecord record) { * close System.err. */ @Override - public void close() { + public synchronized void close() { flush(); } - -} \ No newline at end of file +} diff --git a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployConsoleOutFilter.java b/core/src/main/java/oracle/weblogic/deploy/logging/StdoutFilter.java similarity index 68% rename from core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployConsoleOutFilter.java rename to core/src/main/java/oracle/weblogic/deploy/logging/StdoutFilter.java index 085db33dc7..5a7644808f 100644 --- a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployConsoleOutFilter.java +++ b/core/src/main/java/oracle/weblogic/deploy/logging/StdoutFilter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle Corporation and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2022, Oracle Corporation and/or its affiliates. * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ package oracle.weblogic.deploy.logging; @@ -12,16 +12,14 @@ * This Class queries the information in the LogRecord to determine if it can be written to the OutputStream * associated with standard console log record types. */ -public class WLSDeployConsoleOutFilter implements Filter { - +public class StdoutFilter implements Filter { @Override - public boolean isLoggable(LogRecord record) { + public boolean isLoggable(LogRecord logRecord) { boolean stdOut = true; - int level = record.getLevel() == null ? 0 : record.getLevel().intValue(); + int level = logRecord.getLevel() == null ? 0 : logRecord.getLevel().intValue(); if (level == Level.WARNING.intValue() || level == Level.SEVERE.intValue()) { stdOut = false; } return stdOut; } - -} \ No newline at end of file +} diff --git a/core/src/main/java/oracle/weblogic/deploy/logging/StdoutHandler.java b/core/src/main/java/oracle/weblogic/deploy/logging/StdoutHandler.java new file mode 100644 index 0000000000..9edf693404 --- /dev/null +++ b/core/src/main/java/oracle/weblogic/deploy/logging/StdoutHandler.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2019, 2022, Oracle Corporation and/or its affiliates. + * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. + */ +package oracle.weblogic.deploy.logging; + +import java.util.logging.LogRecord; +import java.util.logging.StreamHandler; + +/** + * This Class extends the StreamHandler to write log records to STDOUT. + */ +@SuppressWarnings("unused") +public class StdoutHandler extends StreamHandler { + + public StdoutHandler() { + super(); + setOutputStream(System.out); + } + + @Override + public synchronized void publish(LogRecord logRecord) { + super.publish(logRecord); + flush(); + } + + /** + * Override StreamHandler.close to do a flush but not + * to close the output stream. That is, we do not + * close System.out. + */ + @Override + public synchronized void close() { + flush(); + } +} diff --git a/core/src/main/java/oracle/weblogic/deploy/logging/SummaryHandler.java b/core/src/main/java/oracle/weblogic/deploy/logging/SummaryHandler.java index ad59aad8a9..fa377a38b5 100644 --- a/core/src/main/java/oracle/weblogic/deploy/logging/SummaryHandler.java +++ b/core/src/main/java/oracle/weblogic/deploy/logging/SummaryHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2019, Oracle Corporation and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2022, Oracle Corporation and/or its affiliates. * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ package oracle.weblogic.deploy.logging; @@ -14,39 +14,37 @@ import java.util.logging.LogRecord; import java.util.logging.MemoryHandler; +import oracle.weblogic.deploy.util.StringUtils; import oracle.weblogic.deploy.util.WLSDeployContext; -import oracle.weblogic.deploy.util.WLSDeployExit; import oracle.weblogic.deploy.util.WebLogicDeployToolingVersion; +import static oracle.weblogic.deploy.logging.WLSDeployLoggingConfig.WLSDEPLOY_SUMMARY_STDOUT_HANDLER; /** * This class save the log records logged by the tool at Info level or greater. The WLSDeployExit exit method will * call this Handler to publish the messages, along with the total of the log records, by Level category. * - * The WLSDeployCustomizeLoggingConfig adds the properties from this class' getHandlerProperties() to the - * log manager logger properties and adds the handler to the root WLSDEPLOY Logger. See the class for information - * on how to inject this handler into the wlsdeploy root logger. - * - * Before the tool exit, if specified by the caller, an activity summary of the saved logs is displayed to the console. + *

Before the tool exit, if specified by the caller, an activity summary of the saved logs is displayed to the console. * A final total of the records logged by the tool for the Level categories indicated above is displayed to the console. * - * @see WLSDeployCustomizeLoggingConfig * @see oracle.weblogic.deploy.util.WLSDeployExit */ -public class SummaryHandler extends Handler implements WLSDeployLogEndHandler { +public class SummaryHandler extends WLSDeployLogEndHandler { private static final String CLASS = SummaryHandler.class.getName(); - private static final String LEVEL_PROPERTY = "level"; - private static final String TARGET_PROPERTY = "target"; - private static final String FORMATTER_PROPERTY = "formatter"; - private static final String SIZE_PROPERTY = "size"; - private static final int DEFAULT_SIZE = 3000; - - private PlatformLogger LOGGER = WLSDeployLogFactory.getLogger("wlsdeploy.exit"); - private int bufferSize; + + private static final String LEVEL_PROPERTY = ".level"; + private static final String TARGET_PROPERTY = ".target"; + private static final String SIZE_PROPERTY = ".size"; + private static final int DEFAULT_MEMORY_BUFFER_SIZE = 3000; + private static final String DEFAULT_SIZE_PROPERTY_VALUE = Integer.toString(DEFAULT_MEMORY_BUFFER_SIZE); + + private final int bufferSize; private WLSDeployContext context; + private boolean suppressOutput = false; - private Handler topTarget; - private List handlers = new ArrayList<>(); + private final PlatformLogger LOGGER; + private final Handler outputTargetHandler; + private final List handlers = new ArrayList<>(); private boolean closed = false; /** @@ -54,38 +52,65 @@ public class SummaryHandler extends Handler implements WLSDeployLogEndHandler { */ public SummaryHandler() { super(); - configure(); + LOGGER = WLSDeployLogFactory.getLogger("wlsdeploy.exit"); + this.outputTargetHandler = getOutputTargetHandler(); + + this.bufferSize = getMemoryBufferSize(CLASS + SIZE_PROPERTY); - LOGGER.setLevel(Level.INFO); addLevelHandler(Level.WARNING); addLevelHandler(Level.SEVERE); } + /** + * The WLSDeployLoggingConfig will call this method to add the SummaryHandler properties to the logging.properties + * files. If the logging.properties already contains the property, the property in this list will be ignored. + * + * @return properties to set in logging.properties + */ + static void addHandlerProperties(Properties logProps) { + if (!logProps.containsKey(CLASS + LEVEL_PROPERTY)) { + logProps.setProperty(CLASS + LEVEL_PROPERTY, Level.INFO.getName()); + } + logProps.setProperty(CLASS + TARGET_PROPERTY, WLSDEPLOY_SUMMARY_STDOUT_HANDLER); + + // If the user has overridden the size property, don't reset it. + // + if (!logProps.containsKey(CLASS + SIZE_PROPERTY)) { + logProps.setProperty(CLASS + SIZE_PROPERTY, DEFAULT_SIZE_PROPERTY_VALUE); + } + } + /** * Tally and save the log record if it matches one of the category Level handlers. Once the summary has completed, * all further log records will be ignored. * - * @param record to tally and save in handler with matching Level category + * @param logRecord to tally and save in handler with matching Level category */ @Override - public synchronized void publish(LogRecord record) { + public synchronized void publish(LogRecord logRecord) { // after close, take yourself out of the mix. The stored up log messages are going to go to the // console handler anyway if (!closed) { for (Handler handler : handlers) { - handler.publish(record); + handler.publish(logRecord); } } } + /** + * {@inheritDoc} + */ @Override public void flush() { - topTarget.flush(); + outputTargetHandler.flush(); } + /** + * {@inheritDoc} + */ @Override public void close() throws SecurityException { - topTarget.close(); + outputTargetHandler.close(); } /** @@ -98,40 +123,17 @@ public void close() throws SecurityException { @Override public synchronized void logEnd(WLSDeployContext modelContext) { closed = true; - String METHOD = "push"; + final String METHOD = "logEnd"; LOGGER.entering(modelContext, CLASS, METHOD); this.context = modelContext; - summaryHead(topTarget); + summaryHead(outputTargetHandler); for (LevelHandler handler : handlers) { handler.push(); } - summaryTail(topTarget); + summaryTail(outputTargetHandler); LOGGER.exiting(CLASS, METHOD); } - /** - * The WLSDeployLoggingConfig will call this method to add the SummaryHandler properties to the logging.properties - * files. If the logging.properties already contains the property, the property in this list will be ignored. - * - * @return properties to set in logging.properties - */ - public static Properties getHandlerProperties() { - Properties properties = new Properties(); - properties.setProperty(LEVEL_PROPERTY, Level.INFO.getName()); - properties.setProperty(TARGET_PROPERTY, WLSDeployLoggingConfig.getStdoutHandler()); - properties.setProperty(FORMATTER_PROPERTY, WLSDeployConsoleFormatter.class.getName()); - return properties; - } - - /** - * Find the summary handler instance in the logging setup. - * If not found, return null. - * @return the summary handler instance, or null if not found. - */ - public static SummaryHandler findInstance() { - return (SummaryHandler) WLSDeployExit.findHandler(SummaryHandler.class); - } - /** * Returns the highest level of the messages in the summary. * If no messages are found, the level INFO is returned. @@ -164,23 +166,56 @@ public int getMessageCount(Level level) { return 0; } + /////////////////////////////////////////////////////////////////////////////////////////////// + // Private helper methods // + /////////////////////////////////////////////////////////////////////////////////////////////// + private void addLevelHandler(Level level) { - LevelHandler handler; - Handler levelTarget = getConsoleHandler(); - levelTarget.setFormatter(new SummaryFormatter(level)); - handler = new LevelHandler(levelTarget, bufferSize, level); - handler.setLevel(level); - handler.setFilter(getFilter()); - handlers.add(handler); + Handler levelTargetHandler = getLevelHandlerOutputTargetHandler(level); + + LevelHandler levelHandler = new LevelHandler(levelTargetHandler, bufferSize, level); + levelHandler.setFilter(null); + levelHandler.setLevel(level); + handlers.add(levelHandler); } - void summaryHead(Handler handler) { + private Handler getOutputTargetHandler() { + Handler summaryStdoutHandler = new WLSDeploySummaryStdoutHandler(); + summaryStdoutHandler.setFormatter(new TotalFormatter()); + summaryStdoutHandler.setFilter(null); + + // If the user turns off the SummaryHandler, turn off the SummaryStdoutHandler instead + // + LogManager manager = LogManager.getLogManager(); + String levelProperty = manager.getProperty(CLASS + LEVEL_PROPERTY); + if (Level.OFF.toString().equals(levelProperty)) { + suppressOutput = true; + summaryStdoutHandler.setLevel(Level.OFF); + } else { + summaryStdoutHandler.setLevel(Level.INFO); + } + return summaryStdoutHandler; + } + + private Handler getLevelHandlerOutputTargetHandler(Level level) { + Handler handler = new WLSDeploySummaryStdoutHandler(); + handler.setFormatter(new SummaryFormatter(level)); + handler.setFilter(null); + if (suppressOutput) { + handler.setLevel(Level.OFF); + } else { + handler.setLevel(level); + } + return handler; + } + + private void summaryHead(Handler handler) { handler.publish(getLogRecord("WLSDPLY-21003", context.getProgramName(), WebLogicDeployToolingVersion.getVersion(), context.getVersion(), context.getWlstMode())); } - void summaryTail(Handler handler) { - StringBuffer buffer = new StringBuffer(); + private void summaryTail(Handler handler) { + StringBuilder buffer = new StringBuilder(); java.util.Formatter fmt = new java.util.Formatter(buffer); for (LevelHandler levelHandler : handlers) { if (levelHandler.getTotalRecords() >= 0) { @@ -190,17 +225,44 @@ void summaryTail(Handler handler) { handler.publish(getLogRecord("WLSDPLY-21002", buffer)); } - private class TotalFormatter extends Formatter { + private int getMemoryBufferSize(String sizePropertyName) { + String sizePropertyValue = LogManager.getLogManager().getProperty(sizePropertyName); - @Override - public synchronized String format(LogRecord record) { - return System.lineSeparator() + formatMessage(record) + System.lineSeparator(); + int size = DEFAULT_MEMORY_BUFFER_SIZE; + if (!StringUtils.isEmpty(sizePropertyValue)) { + try { + size = Integer.parseInt(sizePropertyValue); + } catch (NumberFormatException nfe) { + // Best effort only... + } } + return size; + } + private LogRecord getLogRecord(String msg, Object... params) { + LogRecord logRecord = new LogRecord(Level.INFO, msg); + logRecord.setLoggerName(LOGGER.getName()); + if (params != null && params.length != 0) { + logRecord.setParameters(params); + } + logRecord.setSourceClassName(CLASS); + logRecord.setSourceMethodName(""); + logRecord.setResourceBundle(LOGGER.getUnderlyingLogger().getResourceBundle()); + return logRecord; } - private class SummaryFormatter extends Formatter { + /////////////////////////////////////////////////////////////////////////////////////////////// + // Private helper classes // + /////////////////////////////////////////////////////////////////////////////////////////////// + private class TotalFormatter extends Formatter { + @Override + public synchronized String format(LogRecord logRecord) { + return System.lineSeparator() + formatMessage(logRecord) + System.lineSeparator(); + } + } + + private class SummaryFormatter extends Formatter { private final String MSG_FORMAT = " %1$5d. %2$s: %3$s" + System.lineSeparator(); private final String INTERNAL = System.lineSeparator() + "%s" + System.lineSeparator() + System.lineSeparator(); private int sequence = 0; @@ -211,13 +273,13 @@ public SummaryFormatter(Level level) { } @Override - public synchronized String format(LogRecord record) { + public synchronized String format(LogRecord logRecord) { String message = ""; - String msgId = record.getMessage(); + String msgId = logRecord.getMessage(); if (msgId.indexOf('{') >= 0) { msgId = null; } - String formatted = formatMessage(record); + String formatted = formatMessage(logRecord); if (msgId != null && !msgId.equals(formatted)) { // this has a msg id. don't post any that don't have msg id. message = String.format(MSG_FORMAT, ++sequence, msgId, formatted); @@ -232,7 +294,6 @@ public String getHead(Handler handler) { } private class LevelHandler extends MemoryHandler { - private int totalRecords; LevelHandler(Handler handler, int size, Level level) { @@ -241,54 +302,15 @@ private class LevelHandler extends MemoryHandler { } @Override - public synchronized void publish(LogRecord record) { - if (record.getLevel().intValue() == getLevel().intValue()) { + public synchronized void publish(LogRecord logRecord) { + if (logRecord.getLevel().equals(getLevel())) { ++totalRecords; - super.publish(record); + super.publish(logRecord); } } - public synchronized void push() { - super.push(); - } + int getTotalRecords() { return totalRecords; } - - } - - private void configure() { - LogManager manager = LogManager.getLogManager(); - topTarget = getConsoleHandler(); - topTarget.setFormatter(new TotalFormatter()); - bufferSize = getSize(manager.getProperty(getClass().getName() + "." + SIZE_PROPERTY)); - } - - private int getSize(String propSize) { - Integer handlerSize; - try { - handlerSize = Integer.valueOf(propSize); - } catch (NumberFormatException nfe) { - handlerSize = DEFAULT_SIZE; - } - return handlerSize; } - - private Handler getConsoleHandler() { - Handler handler = LoggingUtils.getHandlerInstance(WLSDeployLoggingConfig.getStdoutHandler()); - handler.setFilter(null); - return handler; - } - - private LogRecord getLogRecord(String msg, Object... params) { - LogRecord record = new LogRecord(Level.INFO, msg); - record.setLoggerName(LOGGER.getName()); - if (params != null && params.length != 0) { - record.setParameters(params); - } - record.setSourceClassName(CLASS); - record.setSourceMethodName(""); - record.setResourceBundle(LOGGER.getUnderlyingLogger().getResourceBundle()); - return record; - } - } diff --git a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployCustomizeLoggingConfig.java b/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployCustomizeLoggingConfig.java deleted file mode 100644 index f69d1c73eb..0000000000 --- a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployCustomizeLoggingConfig.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2018, 2019, Oracle Corporation and/or its affiliates. All rights reserved. - * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. - */ -package oracle.weblogic.deploy.logging; - -import oracle.weblogic.deploy.util.StringUtils; - -import java.lang.reflect.Method; -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -/** - * Use this class to add custom handlers to the root WLSDEPLOY logger. The WLSDeployLoggingConfig - * loads the properties to the LogManager. . - * - *

You must add this class to the -Djava.util.logging.config.class parameter before the tool JVM is started. - * To inject one or more handlers into the WLSDEPLOY logger, you may either add the comma separated list to the - * logger.properties file as WLSDEPLOY_LOGGER_NAME.handlers=list, or set the list on the environment variable - * WLSDEPLOY_LOG_HANDLERS_ENV_VARIABLE. The property in the logging.properties file takes precedence - * over the environment variable. - * - *

This class will check each handler in the list to see if it has implemented the WLSDEPLOY_HANDLER_METHOD. - * This method returns a handler's properties. Any property that already exists in the logging.properties - * will be discarded - as logging.properties takes precedence. Any property that does not start with the handler - * class name will be rejected. This class' ONLY purpose is to dynamically add a handler and/or its properties to the - * WLSDEPLOY root logger. - * - *

The WLSDEPLOY logger is instantiated by WLSDeployLoggingConfig (and thus, the handlers are - * instantiated). The WLSDEPLOY logger's parameters are not inherited by a child logger unless the - * parameter instances already exist before the child logger is added. - */ -public class WLSDeployCustomizeLoggingConfig extends WLSDeployLoggingConfig { - - private static final String WLSDEPLOY_HANDLER_PROP = WLSDEPLOY_LOGGER_NAME + ".handlers"; - private static final String WLSDEPLOY_HANDLER_METHOD = "getHandlerProperties"; - - /** - * Check the logging.properties file for a "WLSDEPLOY".handlers property. If the property does not exist, - * check to see if the WLSDEPLOY_LOG_HANDLERS_ENV_VARIABLE environment variable has been set. - * - *

Check each handler to see if has implemented the WLSDEPLOY_HANDLER_METHOD. A property - * returned from the method is added to the provided properties if the property does not exist in the list. - * - * @param programName name of the tool calling this method - * @param logProps properties comprised by the WLSDeployLoggingConfig class as the base list - */ - @Override - public void customizeLoggingProperties(String programName, Properties logProps) { - List> classList = new ArrayList<>(); - for (String handlerName : findExtraHandlers(logProps)) { - classList.add(getHandlerClass(handlerName)); - } - List handlerList = new ArrayList<>(); - for (Class handler : classList) { - handlerList.add(handler.getName()); - addHandlerProperties(logProps, handler); - } - logProps.setProperty(WLSDEPLOY_HANDLER_PROP, StringUtils.getCommaSeparatedListString(handlerList)); - } - - private static Set findExtraHandlers(Properties logProps) { - // The handlers are applied in order - process environment variable first, then logging properties - Set handlers = new HashSet<>(); - String[] addTo = StringUtils.splitCommaSeparatedList(System.getenv(WLSDEPLOY_LOG_HANDLERS_ENV_VARIABLE)); - if (addTo.length > 0) { - handlers.addAll(Arrays.asList(addTo)); - } - addTo = StringUtils.splitCommaSeparatedList(logProps.getProperty(WLSDEPLOY_HANDLER_PROP)); - if (addTo.length > 0) { - handlers.addAll(Arrays.asList(addTo)); - } - return handlers; - } - - private static Class getHandlerClass(String handlerName) { - return LoggingUtils.getHandlerClass(handlerName); - } - - private static void addHandlerProperties(Properties logProps, Class clazz) { - // Uncomment to debug the properties - // LoggingUtils.printLogProperties(logProps, "Before: "); - Properties props = null; - // a forEach would be good here! - String clazzName = clazz.getName(); - Set propSet = logProps.stringPropertyNames(); - try { - // only look in this class - Method method = clazz.getDeclaredMethod(WLSDEPLOY_HANDLER_METHOD); - props = (Properties)method.invoke(null); - } catch (NoSuchMethodException nsm) { - return; - } catch (Exception e) { - String message = MessageFormat.format("Unable to successfully populate properties for handler {0} " + - "so skipping logging configuration : {1}", clazzName, e.getLocalizedMessage()); - System.err.println(message); - System.exit(ERROR_EXIT_CODE); - } - - if (props != null) { - for (Map.Entry listItem : props.entrySet()) { - if (listItem.getKey() instanceof String && listItem.getValue() instanceof String) { - // requires the handler property name without the handler class name - // this method will add the class to make sure the handler is not setting global properties - // or properties for other handlers - String property = clazzName + '.' + listItem.getKey(); - if (!propSet.contains(property)) { - // logging.properties property takes precedent - logProps.setProperty(property, (String)listItem.getValue()); - } - } - } - } - // Uncomment to debug the log properties - // LoggingUtils.printLogProperties(logProps, "After: "); - } - -} diff --git a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLogEndHandler.java b/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLogEndHandler.java index fd8aa92117..a205b9dc09 100644 --- a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLogEndHandler.java +++ b/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLogEndHandler.java @@ -1,15 +1,21 @@ /* - * Copyright (c) 2018, 2019, Oracle Corporation and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2022, Oracle Corporation and/or its affiliates. * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ package oracle.weblogic.deploy.logging; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Handler; + import oracle.weblogic.deploy.util.WLSDeployContext; +import static oracle.weblogic.deploy.logging.WLSDeployLoggingConfig.WLSDEPLOY_SUMMARY_HANDLER; + /** - * This interface should be used by a Logger Handler that wishes to perform some action or clean-up - * before the wlsdeploy tool exits. A class that implements this interface should include - * the appropriate wrap-up action in the logEnd method. + * This abstract class must be extended by any handler that wishes to perform some action or clean-up + * before the wlsdeploy tool exits. A class that extends this class should include the appropriate wrap-up + * action in its logEnd method. * *

If the tool calls the WLSDeployExit.exit(), that method will search the Handlers on all WLSDEPLOY * loggers. If a handler implements this interface, the logEnd method is called. The handlers' methods are called @@ -18,13 +24,65 @@ * * @see oracle.weblogic.deploy.util.WLSDeployExit */ -public interface WLSDeployLogEndHandler { +public abstract class WLSDeployLogEndHandler extends Handler { + private static final List endHandlers = new ArrayList<>(1); + + /** + * The constructor. + */ + protected WLSDeployLogEndHandler() { + synchronized (WLSDeployLogEndHandler.class) { + endHandlers.add(this); + } + } + + /** + * Get the list of handlers that are WLSDeployLogEndHandlers. + * + * @return the list of handlers that are WLSDeployLogEndHandlers + */ + public static synchronized List getEndHandlers() { + return new ArrayList<>(endHandlers); + } + + /** + * Get the SummaryHandler instance. + * + * @return the SummaryHandler or null if there is no SummaryHandler instance + */ + public static synchronized WLSDeployLogEndHandler getSummaryHandler() { + WLSDeployLogEndHandler summaryHandler = null; + for (WLSDeployLogEndHandler handler : endHandlers) { + if (WLSDEPLOY_SUMMARY_HANDLER.equals(handler.getClass().getName())) { + summaryHandler = handler; + break; + } + } + return summaryHandler; + } + + // For Python unit tests only + @SuppressWarnings("unused") + public static synchronized void clearHandlers() { + endHandlers.clear(); + } + + /** + * Invoke the logEnd() method on every WLSDeployLogEndHandler handler. + * + * @param context the context object + */ + @SuppressWarnings("unused") + public static synchronized void closeLog(WLSDeployContext context) { + for (WLSDeployLogEndHandler endHandler : endHandlers) { + endHandler.logEnd(context); + } + } /** * The handler performs any wrap-up action. * * @param context containing contextual information about the tool */ - void logEnd(WLSDeployContext context); - -} \ No newline at end of file + public abstract void logEnd(WLSDeployContext context); +} diff --git a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLogFactory.java b/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLogFactory.java index 1a366223f6..a3024ca5fe 100644 --- a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLogFactory.java +++ b/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLogFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2019, Oracle Corporation and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2022, Oracle Corporation and/or its affiliates. * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ package oracle.weblogic.deploy.logging; diff --git a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLogFormatter.java b/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLogFormatter.java index 6c96ee51bb..9a218f8d36 100644 --- a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLogFormatter.java +++ b/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLogFormatter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2019, Oracle Corporation and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2022, Oracle Corporation and/or its affiliates. * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ package oracle.weblogic.deploy.logging; @@ -22,9 +22,9 @@ public class WLSDeployLogFormatter extends Formatter { private static final String DATE_FORMAT_STRING = "####<{0,date} {0,time}>"; private static final String LINE_SEPARATOR = System.getProperty("line.separator"); - private Object[] args; - private MessageFormat formatter; - private Date date; + private final Object[] args; + private final MessageFormat formatter; + private final Date date; /** * The constructor. @@ -38,14 +38,14 @@ public WLSDeployLogFormatter() { /** * Formats the log record. * - * @param record the log record + * @param logRecord the log record * @return the formatted log record */ @Override - public synchronized String format(LogRecord record) { + public synchronized String format(LogRecord logRecord) { StringBuilder sb = new StringBuilder(); - date.setTime(record.getMillis()); + date.setTime(logRecord.getMillis()); args[0] = date; StringBuffer text = new StringBuffer(); @@ -54,28 +54,28 @@ public synchronized String format(LogRecord record) { // Level sb.append(" <"); - sb.append(record.getLevel().getLocalizedName()); + sb.append(logRecord.getLevel().getLocalizedName()); sb.append('>'); // Class name sb.append(" <"); - String source = record.getSourceClassName(); + String source = logRecord.getSourceClassName(); if (source != null) { sb.append(source.substring(source.lastIndexOf('.') + 1)); } else { - sb.append(record.getLoggerName()); + sb.append(logRecord.getLoggerName()); } sb.append('>'); // Method name sb.append(" <"); - if (record.getSourceMethodName() != null) { - sb.append(record.getSourceMethodName()); + if (logRecord.getSourceMethodName() != null) { + sb.append(logRecord.getSourceMethodName()); } sb.append('>'); - String messageKey = record.getMessage(); - String message = formatMessage(record); + String messageKey = logRecord.getMessage(); + String message = formatMessage(logRecord); if (messageKey != null) { sb.append(" <"); @@ -86,10 +86,10 @@ public synchronized String format(LogRecord record) { } sb.append(" <"); sb.append(message); - if (record.getThrown() != null) { + if (logRecord.getThrown() != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); - record.getThrown().printStackTrace(pw); + logRecord.getThrown().printStackTrace(pw); pw.close(); sb.append(LINE_SEPARATOR); sb.append(sw); diff --git a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLoggingConfig.java b/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLoggingConfig.java index 546753722e..5f96a03a80 100644 --- a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLoggingConfig.java +++ b/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLoggingConfig.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, Oracle Corporation and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2022, Oracle Corporation and/or its affiliates. * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ package oracle.weblogic.deploy.logging; @@ -24,24 +24,33 @@ import oracle.weblogic.deploy.util.StringUtils; /** - * The logging config class for use by wls-deploy and friends. + * The logging config class that configures the wlsdeploy tool logging. */ public class WLSDeployLoggingConfig { private static final String DEFAULT_PROGRAM_NAME = "unknown-test"; + public static final String WLSDEPLOY_LOGGER_NAME = "wlsdeploy"; private static final List WLSDEPLOY_ROOT_LOGGERS = - Collections.singletonList("oracle.weblogic.deploy"); + Collections.singletonList(WLSDEPLOY_LOGGER_NAME); private static final String DEFAULT_LOG_CONFIG_FILE_NAME = "logging.properties"; - private static final String LOG_NAME_PATTERN = "%s.log"; + private static final String LOG_NAME_PATTERN = "%s%s%s.log"; private static final String HANDLERS_PROP = "handlers"; private static final String CONFIG_PROP = "config"; private static final String WLSDEPLOY_STDOUT_CONSOLE_HANDLER = - "oracle.weblogic.deploy.logging.WLSDeployLoggingStdoutHandler"; + "oracle.weblogic.deploy.logging.StdoutHandler"; private static final String WLSDEPLOY_STDERR_CONSOLE_HANDLER = - "oracle.weblogic.deploy.logging.WLSDeployLoggingStderrHandler"; + "oracle.weblogic.deploy.logging.StderrHandler"; + static final String WLSDEPLOY_SUMMARY_HANDLER = "oracle.weblogic.deploy.logging.SummaryHandler"; + static final String WLSDEPLOY_SUMMARY_STDOUT_HANDLER = + "oracle.weblogic.deploy.logging.WLSDeploySummaryStdoutHandler"; private static final String FILE_HANDLER = "java.util.logging.FileHandler"; - public static final String WLSDEPLOY_LOGGER_NAME = "wlsdeploy"; + private static final List DEFAULT_HANDLERS = new ArrayList<>(Arrays.asList( + WLSDEPLOY_STDOUT_CONSOLE_HANDLER, + WLSDEPLOY_STDERR_CONSOLE_HANDLER, + WLSDEPLOY_SUMMARY_HANDLER, + FILE_HANDLER + )); private static final String HANDLER_LEVEL_PROP = ".level"; private static final String HANDLER_FILTER_PROP = ".filter"; @@ -50,18 +59,18 @@ public class WLSDeployLoggingConfig { private static final String HANDLER_LIMIT_PROP = ".limit"; private static final String HANDLER_COUNT_PROP = ".count"; private static final String HANDLER_APPEND_PROP = ".append"; + private static final String HANDLER_SIZE_PROP = ".size"; private static final String LOGGER_LEVEL_PROP = HANDLER_LEVEL_PROP; + private static final String CONSOLE_FORMATTER_PROP = ConsoleFormatter.class.getName(); + private static final String STDOUT_FILTER_PROP = StdoutFilter.class.getName(); + private static final String STDERR_FILTER_PROP = StderrFilter.class.getName(); private static final String DEFAULT_FILE_HANDLER_LEVEL = Level.ALL.toString(); - private static final String DEFAULT_CONSOLE_HANDLER_LEVEL = Level.INFO.toString(); - private static final String DEFAULT_WLSLCM_ROOT_LOGGER_LEVEL = Level.INFO.toString(); - private static final String DEFAULT_CONSOLE_FORMATTER_PROP = - "oracle.weblogic.deploy.logging.WLSDeployConsoleFormatter"; - private static final String DEFAULT_STDOUT_FILTER_PROP = - "oracle.weblogic.deploy.logging.WLSDeployConsoleOutFilter"; - private static final String DEFAULT_STDERR_FILTER_PROP = - "oracle.weblogic.deploy.logging.WLSDeployConsoleErrorFilter"; + private static final String DEFAULT_STDOUT_HANDLER_LEVEL = Level.INFO.toString(); + private static final String DEFAULT_STDERR_HANDLER_LEVEL = Level.INFO.toString(); + + private static final String DEFAULT_WLSDEPLOY_ROOT_LOGGER_LEVEL = Level.INFO.toString(); private static final String DEFAULT_FILE_HANDLER_LIMIT = "0"; private static final String DEFAULT_FILE_HANDLER_COUNT = "1"; private static final String DEFAULT_FILE_HANDLER_APPEND = "false"; @@ -137,9 +146,7 @@ public WLSDeployLoggingConfig() { } setLoggingPropertiesFile(loggingConfigFile); - InputStream logPropertiesStream = null; - try { - logPropertiesStream = processLoggingPropertiesFile(programName, loggingConfigFile); + try (InputStream logPropertiesStream = processLoggingPropertiesFile(programName, loggingConfigFile)) { LogManager.getLogManager().readConfiguration(logPropertiesStream); } catch (IOException ioe) { String message = MessageFormat.format("Failed to process {0}: {1}", loggingConfigFile.getAbsolutePath(), @@ -147,59 +154,34 @@ public WLSDeployLoggingConfig() { System.err.println(message); ioe.printStackTrace(System.err); System.exit(ERROR_EXIT_CODE); - } finally { - if (logPropertiesStream != null) { - try { - logPropertiesStream.close(); - } catch (IOException ignore) { - // nothing to do... - } - } } PlatformLogger logger = WLSDeployLogFactory.getLogger(WLSDEPLOY_LOGGER_NAME); // make sure that this is the first logger logger.info("The {0} program will write its log to {1}", programName, logFileName); } - public static synchronized File getLoggingDirectory() { - return new File(loggingDirectory.getAbsolutePath()); - } - - public static synchronized File getLoggingPropertiesFile() { - return new File(loggingPropertiesFile.getAbsolutePath()); - } - /** - * Return the console handler that writes log records to STDOUT. - * @return Class name of the console handler that writes to STDOUT - */ - public static String getStdoutHandler() { - return WLSDEPLOY_STDOUT_CONSOLE_HANDLER; - } - - /** - * Return the console handler that writes log records to STDERR. - * @return Class name of the console handler that writes to STDERR + * Get the logging directory. + * + * @return the logging directory */ - public static String getStderrHandler() { - return WLSDEPLOY_STDERR_CONSOLE_HANDLER; + public static synchronized File getLoggingDirectory() { + return new File(loggingDirectory.getAbsolutePath()); } /** - * To augment the logging properties with custom properties, extend this class and overwrite this method. - * The method should add applicable properties to the logProps. These properties will be loaded into the LogManager - * and available to Logger instances. Do not instantiate Loggers in this class as the reload will reset the - * Loggers. + * Get the logging.properties file. * - * @param programName the name of the tool running, useful for messages. - * @param logProps property instance to which to add log properties in string format, key=value + * @return the logging.properties file */ - public void customizeLoggingProperties(String programName, Properties logProps) { - // override to customize + @SuppressWarnings("unused") + public static synchronized File getLoggingPropertiesFile() { + return new File(loggingPropertiesFile.getAbsolutePath()); } /////////////////////////////////////////////////////////////////////////// // Private helper methods // /////////////////////////////////////////////////////////////////////////// + private InputStream processLoggingPropertiesFile(String programName, File logPropsFile) throws IOException { Properties logProps = new Properties(); @@ -220,60 +202,125 @@ private InputStream processLoggingPropertiesFile(String programName, File logPro } private void augmentLoggingProperties(String programName, Properties logProps) { + List handlers = updateHandlers(processLoggingPropertiesFileContents(logProps), logProps); + + // At this point, we should have a properties object with any + // handler configuration we care about removed, so we can safely + // add our configuration. + // + for (String handler : DEFAULT_HANDLERS) { + if (handlers.contains(handler)) { + configureHandler(programName, handler, logProps); + } + } + ensureRootLoggerLevelIsSet(logProps); + + // Uncomment to debug log properties that will be passed to the LogManager + // LoggingUtils.printLogProperties(logProps, "Final log properties : "); + } + + private List processLoggingPropertiesFileContents(Properties logProps) { Set keys = logProps.stringPropertyNames(); - List handlers = new ArrayList<>(); + List handlers = null; for (String key : keys) { if (HANDLERS_PROP.equals(key)) { String val = logProps.getProperty(key); - handlers = Arrays.asList(StringUtils.splitCommaSeparatedList(val)); - } else if (isKeyKnownHandlerProperty(key) || CONFIG_PROP.equals(key)) { + handlers = new ArrayList<>(Arrays.asList(StringUtils.splitCommaSeparatedList(val))); + } else if (isFilteredHandlerProperty(key, logProps) || CONFIG_PROP.equals(key)) { logProps.remove(key); } } + return handlers; + } - // At this point, we should have a properties object with any - // handler configuration we care about removed so we can safely - // add our configuration. - // - String consoleHandler = getStdoutHandler(); - if (!handlers.contains(consoleHandler)) { - handlers.add(consoleHandler); + private List updateHandlers(List inputHandlers, Properties logProps) { + List handlers = inputHandlers; + String handlersEnvVar = System.getenv(WLSDEPLOY_LOG_HANDLERS_ENV_VARIABLE); + if (handlersEnvVar != null) { + handlers = new ArrayList<>(Arrays.asList(StringUtils.splitCommaSeparatedList(handlersEnvVar))); } - consoleHandler = getStderrHandler(); - if (!handlers.contains(consoleHandler)) { - handlers.add(consoleHandler); - } - if (!handlers.contains(FILE_HANDLER)) { - handlers.add(FILE_HANDLER); + + // If the handlers were not explicitly listed in the logging.properties file, + // add the default handlers to the list. + // + if (handlers == null){ + handlers = DEFAULT_HANDLERS; + } else { + // The SummaryStdoutHandler cannot be in the registered handlers list or + // duplicate messages will be logged to stdout. + // + handlers.remove(WLSDEPLOY_SUMMARY_STDOUT_HANDLER); + + // The SummaryHandler is required to collect warning and error messages for + // validation so make sure it is in the list. + // + if (!handlers.contains(WLSDEPLOY_SUMMARY_HANDLER)) { + handlers.add(WLSDEPLOY_SUMMARY_HANDLER); + // If the user omitted the SummaryHandler from the list, we will set its + // level to OFF so that its output will not be written to stdout. + // + logProps.setProperty(WLSDEPLOY_SUMMARY_HANDLER + HANDLER_LEVEL_PROP, Level.OFF.toString()); + } } String handlersListString = StringUtils.getCommaSeparatedListString(handlers); logProps.setProperty(HANDLERS_PROP, handlersListString); + return handlers; + } - customizeLoggingProperties(programName, logProps); + private void configureHandler(String programName, String handler, Properties logProps) { + switch(handler) { + case WLSDEPLOY_STDOUT_CONSOLE_HANDLER: + configureStdoutConsoleHandler(logProps); + break; - logFileName = configureFileHandler(programName, logProps); - configureConsoleHandler(logProps); + case WLSDEPLOY_STDERR_CONSOLE_HANDLER: + configureStderrConsoleHandler(logProps); + break; + case WLSDEPLOY_SUMMARY_HANDLER: + SummaryHandler.addHandlerProperties(logProps); + break; + + case FILE_HANDLER: + logFileName = configureFileHandler(programName, logProps); + break; + + default: + String message = MessageFormat.format("{0} failed to configure unrecognized log handler {1}", + programName, handler); + System.err.println(message); + System.exit(ERROR_EXIT_CODE); + } + } + + private void ensureRootLoggerLevelIsSet(Properties logProps) { for (String loggerName : WLSDEPLOY_ROOT_LOGGERS) { String loggerLevelProp = loggerName + LOGGER_LEVEL_PROP; if (!logProps.containsKey(loggerLevelProp)) { - logProps.setProperty(loggerLevelProp, DEFAULT_WLSLCM_ROOT_LOGGER_LEVEL); + logProps.setProperty(loggerLevelProp, DEFAULT_WLSDEPLOY_ROOT_LOGGER_LEVEL); } } - // Uncomment to debug log properties that will be passed to the LogManager - // LoggingUtils.printLogProperties(logProps, "Final log properties : "); } - private static boolean isKeyKnownHandlerProperty(String key) { - return key.startsWith(getStdoutHandler()) || - key.startsWith(getStderrHandler()) || - key.startsWith(FILE_HANDLER); + private static boolean isFilteredHandlerProperty(String key, Properties logProps) { + boolean result = false; + for (String handler : DEFAULT_HANDLERS) { + if (key.startsWith(handler)) { + result = !key.equals(handler + LOGGER_LEVEL_PROP) || !"OFF".equals(logProps.getProperty(key)); + + // Allow the user to override the SummaryHandler's size property. + // + if (result && key.equals(WLSDEPLOY_SUMMARY_HANDLER + HANDLER_SIZE_PROP)) { + result = false; + } + } + } + return result; } private static String configureFileHandler(String programName, Properties logProps) { File logDir = findLoggingDirectory(programName); - String pattern = String.format(logDir.getAbsolutePath() + File.separator + - LOG_NAME_PATTERN, programName); + String pattern = String.format(LOG_NAME_PATTERN, logDir.getAbsolutePath(), File.separator, programName); logProps.setProperty(FILE_HANDLER + HANDLER_PATTERN_PROP, pattern); logProps.setProperty(FILE_HANDLER + HANDLER_FORMATTER_PROP, LOG_FORMATTER); logProps.setProperty(FILE_HANDLER + HANDLER_LEVEL_PROP, DEFAULT_FILE_HANDLER_LEVEL); @@ -283,56 +330,90 @@ private static String configureFileHandler(String programName, Properties logPro return pattern; } - private static void configureConsoleHandler(Properties logProps) { - configureStderrConsoleHandler(logProps); - configureStdoutConsoleHandler(logProps); - } - private static void configureStdoutConsoleHandler(Properties logProps) { - String consoleHandler = getStdoutHandler(); - String debugToStdoutString = System.getProperty(WLSDEPLOY_DEBUG_TO_STDOUT_PROP, DEFAULT_DEBUG_TO_STDOUT); - if (Boolean.parseBoolean(debugToStdoutString)) { - logProps.setProperty(consoleHandler + HANDLER_LEVEL_PROP, Level.ALL.toString()); - } else { - logProps.setProperty(consoleHandler + HANDLER_LEVEL_PROP, DEFAULT_CONSOLE_HANDLER_LEVEL); + String stdoutHandlerLevel = WLSDEPLOY_STDOUT_CONSOLE_HANDLER + HANDLER_LEVEL_PROP; + + // If the log properties already has the level set, don't bother changing it since + // currently, the only way this happens is if the value is OFF. + // + if (logProps.getProperty(stdoutHandlerLevel) == null) { + String debugToStdoutString = System.getProperty(WLSDEPLOY_DEBUG_TO_STDOUT_PROP, DEFAULT_DEBUG_TO_STDOUT); + if (Boolean.parseBoolean(debugToStdoutString)) { + logProps.setProperty(stdoutHandlerLevel, Level.ALL.toString()); + } else { + logProps.setProperty(stdoutHandlerLevel, DEFAULT_STDOUT_HANDLER_LEVEL); + } } - logProps.setProperty(consoleHandler + HANDLER_FORMATTER_PROP, DEFAULT_CONSOLE_FORMATTER_PROP); - logProps.setProperty(consoleHandler + HANDLER_FILTER_PROP, DEFAULT_STDOUT_FILTER_PROP); + logProps.setProperty(WLSDEPLOY_STDOUT_CONSOLE_HANDLER + HANDLER_FORMATTER_PROP, CONSOLE_FORMATTER_PROP); + logProps.setProperty(WLSDEPLOY_STDOUT_CONSOLE_HANDLER + HANDLER_FILTER_PROP, STDOUT_FILTER_PROP); } private static void configureStderrConsoleHandler(Properties logProps) { - String consoleHandler = getStderrHandler(); - logProps.setProperty(consoleHandler + HANDLER_LEVEL_PROP, DEFAULT_CONSOLE_HANDLER_LEVEL); - logProps.setProperty(consoleHandler + HANDLER_FORMATTER_PROP, DEFAULT_CONSOLE_FORMATTER_PROP); - logProps.setProperty(consoleHandler + HANDLER_FILTER_PROP, DEFAULT_STDERR_FILTER_PROP); + String stderrHandlerLevel = WLSDEPLOY_STDERR_CONSOLE_HANDLER + HANDLER_LEVEL_PROP; + + // If the log properties already has the level set, don't bother changing it since + // currently, the only way this happens is if the value is OFF. + // + if (logProps.getProperty(stderrHandlerLevel) == null) { + logProps.setProperty(stderrHandlerLevel, DEFAULT_STDERR_HANDLER_LEVEL); + } + logProps.setProperty(WLSDEPLOY_STDERR_CONSOLE_HANDLER + HANDLER_FORMATTER_PROP, CONSOLE_FORMATTER_PROP); + logProps.setProperty(WLSDEPLOY_STDERR_CONSOLE_HANDLER + HANDLER_FILTER_PROP, STDERR_FILTER_PROP); } private static File findLoggingDirectory(String programName) { + File logDir = checkLogDirectoryEnvironmentVariable(); + + if (logDir == null) { + logDir = checkCurrentDirectoryForLogging(); + } + if (logDir == null) { + logDir = checkTempDirectoryForLogging(programName); + } + + // If we get to this point and haven't found a suitable log directory, fail. + if (logDir == null) { + String message = + MessageFormat.format("{0} was unable to find a writable location for its logs", programName); + System.err.println(message); + System.exit(ERROR_EXIT_CODE); + } + setLoggingDir(logDir); + return logDir; + } + + private static File checkLogDirectoryEnvironmentVariable() { String logLocation = System.getenv(WLSDEPLOY_LOGS_DIRECTORY_ENV_VARIABLE); - File currentDirectory = new File(System.getProperty("user.dir", "")).getAbsoluteFile(); - File tmpDir = new File(System.getProperty("java.io.tmpdir")).getAbsoluteFile(); File logDir = null; - boolean found = false; - if (!StringUtils.isEmpty(logLocation)) { - logDir = new File(logLocation).getAbsoluteFile(); - if ((logDir.exists() && logDir.canWrite()) || (logDir.mkdirs() && logDir.canWrite())) { - found = true; + File tmpLogDir = new File(logLocation).getAbsoluteFile(); + if ((tmpLogDir.exists() && tmpLogDir.canWrite()) || (tmpLogDir.mkdirs() && tmpLogDir.canWrite())) { + logDir = tmpLogDir; } } + return logDir; + } - if (!found && currentDirectory.canWrite()) { - logDir = new File(currentDirectory, "logs"); - if ((logDir.exists() && logDir.canWrite()) || (logDir.mkdirs() && logDir.canWrite())) { - found = true; + private static File checkCurrentDirectoryForLogging() { + File logDir = null; + File currentDirectory = new File(System.getProperty("user.dir", "")).getAbsoluteFile(); + if (currentDirectory.canWrite()) { + File tmpLogDir = new File(currentDirectory, "logs"); + if ((tmpLogDir.exists() && tmpLogDir.canWrite()) || (tmpLogDir.mkdirs() && tmpLogDir.canWrite())) { + logDir = tmpLogDir; } } + return logDir; + } + + private static File checkTempDirectoryForLogging(String programName) { + File logDir = null; - if (!found && tmpDir.canWrite()) { + File tmpDir = new File(System.getProperty("java.io.tmpdir")).getAbsoluteFile(); + if (tmpDir.canWrite()) { try { File parentDir = tmpDir.getCanonicalFile(); logDir = FileUtils.createTempDirectory(parentDir, "wdt-logs"); - found = true; } catch (IOException ioe) { String message = MessageFormat.format("{0} failed to create temporary logs directory in {1}: {2}", programName, tmpDir.getAbsolutePath(), ioe.getMessage()); @@ -340,15 +421,6 @@ private static File findLoggingDirectory(String programName) { System.exit(ERROR_EXIT_CODE); } } - - // If we get to this point and we haven't found a suitable log directory, fail. - if (!found) { - String message = - MessageFormat.format("{0} was unable to find a writable location for its logs", programName); - System.err.println(message); - System.exit(ERROR_EXIT_CODE); - } - setLoggingDir(logDir); return logDir; } @@ -363,5 +435,4 @@ private static synchronized void setLoggingPropertiesFile(File logPropsFile) { loggingPropertiesFile = logPropsFile; } } - } diff --git a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLoggingStdoutHandler.java b/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeploySummaryStdoutHandler.java similarity index 50% rename from core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLoggingStdoutHandler.java rename to core/src/main/java/oracle/weblogic/deploy/logging/WLSDeploySummaryStdoutHandler.java index c3d78033de..e6e69af5a6 100644 --- a/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeployLoggingStdoutHandler.java +++ b/core/src/main/java/oracle/weblogic/deploy/logging/WLSDeploySummaryStdoutHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle Corporation and/or its affiliates. All rights reserved. + * Copyright (c) 2022, Oracle Corporation and/or its affiliates. * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ package oracle.weblogic.deploy.logging; @@ -8,23 +8,18 @@ import java.util.logging.StreamHandler; /** - /** - * This Class extends the StreamHandler to write log records to STDOUT. The "wlsdeploy" Logger - * is configured with an instance of this Handler class and an instance of Class @WLSDeployStderrHandler@ - * to log records to the STDOUT and STDERR output streams. - *

- * Attach a logger or filter to this Handler to direct log records to the STDOUT output stream + * This Class extends the StreamHandler to write log records to STDOUT for the Summary Handler. */ -public class WLSDeployLoggingStdoutHandler extends StreamHandler { +public class WLSDeploySummaryStdoutHandler extends StreamHandler { - public WLSDeployLoggingStdoutHandler() { + public WLSDeploySummaryStdoutHandler() { super(); setOutputStream(System.out); } @Override - public void publish(LogRecord record) { - super.publish(record); + public synchronized void publish(LogRecord logRecord) { + super.publish(logRecord); flush(); } @@ -34,7 +29,7 @@ public void publish(LogRecord record) { * close System.out. */ @Override - public void close() { + public synchronized void close() { flush(); } -} \ No newline at end of file +} diff --git a/core/src/main/java/oracle/weblogic/deploy/logging/package-info.java b/core/src/main/java/oracle/weblogic/deploy/logging/package-info.java index 0e17fb8dfb..f02432e9f8 100644 --- a/core/src/main/java/oracle/weblogic/deploy/logging/package-info.java +++ b/core/src/main/java/oracle/weblogic/deploy/logging/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2019, Oracle Corporation and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2022, Oracle Corporation and/or its affiliates. * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ /** diff --git a/core/src/main/java/oracle/weblogic/deploy/util/WLSDeployExit.java b/core/src/main/java/oracle/weblogic/deploy/util/WLSDeployExit.java index 964a5828c0..b81d459316 100644 --- a/core/src/main/java/oracle/weblogic/deploy/util/WLSDeployExit.java +++ b/core/src/main/java/oracle/weblogic/deploy/util/WLSDeployExit.java @@ -1,19 +1,13 @@ /* - * Copyright (c) 2018, 2019, Oracle Corporation and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2022, Oracle Corporation and/or its affiliates. * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ package oracle.weblogic.deploy.util; -import java.util.ArrayList; -import java.util.LinkedList; import java.util.List; -import java.util.logging.Handler; -import java.util.logging.Logger; -import java.util.Stack; import oracle.weblogic.deploy.logging.PlatformLogger; import oracle.weblogic.deploy.logging.WLSDeployLogEndHandler; -import oracle.weblogic.deploy.logging.WLSDeployLoggingConfig; import oracle.weblogic.deploy.logging.WLSDeployLogFactory; /** @@ -21,9 +15,12 @@ * to exit instead of System.exit. */ public class WLSDeployExit { - private static final String CLASS = WLSDeployExit.class.getName(); - private static final PlatformLogger LOGGER = WLSDeployLogFactory.getLogger("wlsdeploy.util"); + private static final PlatformLogger LOGGER = WLSDeployLogFactory.getLogger("wlsdeploy.exit"); + + private WLSDeployExit() { + // hide the constructor + } /** * Perform any last methods for the tools and exit the JVM. @@ -49,81 +46,13 @@ public static void exit(int error_code) { System.exit(error_code); } - /** - * Returns the first handler that is assignment-compatible with the specified class. - * @param handlerClass the class to check for compatibility - * @return the first matching handler, or null if none is found - */ - public static Handler findHandler(Class handlerClass) { - Stack handlers = reduceList(traverseHandlers(getTopLogList(), new LinkedList())); - while (handlers.size() > 0) { - Handler handler = handlers.pop(); - if(handlerClass.isInstance(handler)) { - return handler; - } - } - return null; - } - - /** - * Call any WLSDeployLogEnd Logger handlers so the handlers can perform end actions. - * - * @param context that contains contextual information about the tool that is currently running - */ - public static void logCleanup(WLSDeployContext context) { - String METHOD = "logCleanup"; + private static void logCleanup(WLSDeployContext context) { + final String METHOD = "logCleanup"; LOGGER.entering(CLASS, METHOD, context); - Stack handlers = reduceList(traverseHandlers(getTopLogList(), new LinkedList())); - while (handlers.size() > 0) { - logEnd(context, (WLSDeployLogEndHandler)handlers.pop()); + List endHandlers = WLSDeployLogEndHandler.getEndHandlers(); + for (WLSDeployLogEndHandler endHandler : endHandlers) { + endHandler.logEnd(context); } LOGGER.exiting(CLASS, METHOD); } - - private static List getTopLogList() { - List loggerList = new ArrayList<>(); - for (Logger logger : PlatformLogger.getLoggers()) { - if (logger.getName().startsWith(WLSDeployLoggingConfig.WLSDEPLOY_LOGGER_NAME)) { - loggerList.add(logger); - } - } - return loggerList; - } - - private static synchronized void logEnd(WLSDeployContext context, WLSDeployLogEndHandler handler) { - handler.logEnd(context); - } - - private static LinkedList traverseHandlers(List loggers, LinkedList handlerList) { - List parents = new ArrayList<>(); - if (loggers.size() > 0) { - for (Logger logger : loggers) { - if (logger.getUseParentHandlers()) { - for (Handler handler : logger.getHandlers()) { - if (WLSDeployLogEndHandler.class.isAssignableFrom(handler.getClass())) { - handlerList.add(handler); - } - Logger parent = logger.getParent(); - if (parent != null) { - parents.add(parent); - } - } - } - } - handlerList = traverseHandlers(parents, handlerList); - } - return handlerList; - } - - private static Stack reduceList(LinkedList handlers) { - Stack reducedList = new Stack<>(); - while (handlers.size() > 0 ){ - Handler bottom = handlers.removeLast(); - if (!reducedList.contains(bottom)) { - reducedList.add(bottom); - } - } - return reducedList; - } - -} \ No newline at end of file +} diff --git a/core/src/main/python/validate.py b/core/src/main/python/validate.py index e8c17d4594..3dee7dc49f 100644 --- a/core/src/main/python/validate.py +++ b/core/src/main/python/validate.py @@ -8,14 +8,13 @@ import sys from java.util.logging import Level +from oracle.weblogic.deploy.logging import WLSDeployLogEndHandler from oracle.weblogic.deploy.util import CLAException from oracle.weblogic.deploy.util import TranslateException from oracle.weblogic.deploy.util import VariableException from oracle.weblogic.deploy.util import WebLogicDeployToolingVersion from oracle.weblogic.deploy.validate import ValidateException -from oracle.weblogic.deploy.logging import SummaryHandler - # Jython tools don't require sys.path modification # imports from local packages start here @@ -172,7 +171,7 @@ def main(args): if model_file_name is not None: __perform_model_file_validation(model_file_name, model_context) - summary_handler = SummaryHandler.findInstance() + summary_handler = WLSDeployLogEndHandler.getSummaryHandler() if summary_handler is not None: summary_level = summary_handler.getMaximumMessageLevel() if summary_level == Level.SEVERE: diff --git a/core/src/main/python/wlsdeploy/tool/validate/validator.py b/core/src/main/python/wlsdeploy/tool/validate/validator.py index 19e1b2de9d..1c38900b94 100644 --- a/core/src/main/python/wlsdeploy/tool/validate/validator.py +++ b/core/src/main/python/wlsdeploy/tool/validate/validator.py @@ -7,7 +7,7 @@ from java.util.logging import Level -from oracle.weblogic.deploy.logging import SummaryHandler +from oracle.weblogic.deploy.logging import WLSDeployLogEndHandler from oracle.weblogic.deploy.util import WLSDeployArchive from oracle.weblogic.deploy.util import VariableException @@ -131,13 +131,16 @@ def validate_in_standalone_mode(self, model_dict, variable_map, archive_file_nam self.__validate_model_file(cloned_model_dict, variable_map, archive_file_name) status = Validator.ValidationStatus.VALID - summary_handler = SummaryHandler.findInstance() + summary_handler = WLSDeployLogEndHandler.getSummaryHandler() if summary_handler is not None: summary_level = summary_handler.getMaximumMessageLevel() if summary_level == Level.SEVERE: status = Validator.ValidationStatus.INVALID elif summary_level == Level.WARNING: status = Validator.ValidationStatus.WARNINGS_INVALID + else: + # TODO - Should really report/throw an error here if the summary logger was not found! + pass if status == Validator.ValidationStatus.VALID or status == Validator.ValidationStatus.INFOS_VALID \ or status == Validator.ValidationStatus.WARNINGS_INVALID: @@ -181,13 +184,16 @@ def validate_in_tool_mode(self, model_dict, variables_file_name=None, archive_fi status = Validator.ValidationStatus.VALID - summary_handler = SummaryHandler.findInstance() + summary_handler = WLSDeployLogEndHandler.getSummaryHandler() if summary_handler is not None: summary_level = summary_handler.getMaximumMessageLevel() if summary_level == Level.SEVERE: status = Validator.ValidationStatus.INVALID elif summary_level == Level.WARNING: status = Validator.ValidationStatus.WARNINGS_INVALID + else: + # TODO - Should really report/throw an error here if the summary logger was not found! + pass if status == Validator.ValidationStatus.VALID or status == Validator.ValidationStatus.INFOS_VALID \ or status == Validator.ValidationStatus.WARNINGS_INVALID: diff --git a/core/src/test/java/oracle/weblogic/deploy/logging/SummaryHandlerTest.java b/core/src/test/java/oracle/weblogic/deploy/logging/SummaryHandlerTest.java new file mode 100644 index 0000000000..86b75ed6be --- /dev/null +++ b/core/src/test/java/oracle/weblogic/deploy/logging/SummaryHandlerTest.java @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022, Oracle Corporation and/or its affiliates. + * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. + */ +package oracle.weblogic.deploy.logging; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class SummaryHandlerTest { + @Test + public void testGetSummaryHandler_ReturnsHandler() { + SummaryHandler handler = new SummaryHandler(); + + WLSDeployLogEndHandler summaryHandler = WLSDeployLogEndHandler.getSummaryHandler(); + assertNotNull(summaryHandler, "SummaryHandler should not be null"); + assertEquals(handler, summaryHandler, "summaryHandler is not the same object"); + } +} diff --git a/core/src/test/python/compare_model_test.py b/core/src/test/python/compare_model_test.py index 1a21925eff..c7313ec389 100644 --- a/core/src/test/python/compare_model_test.py +++ b/core/src/test/python/compare_model_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) 2020, 2021 Oracle and/or its affiliates. +Copyright (c) 2020, 2022 Oracle and/or its affiliates. Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. """ import unittest @@ -10,6 +10,7 @@ from java.util.logging import Level from oracle.weblogic.deploy.compare import CompareException from oracle.weblogic.deploy.logging import SummaryHandler +from oracle.weblogic.deploy.logging import WLSDeployLogEndHandler from oracle.weblogic.deploy.util import PyWLSTException from compare_model import ModelFileDiffer @@ -49,11 +50,33 @@ def setUp(self): # add summary handler to validate logger to check results self._summary_handler = SummaryHandler() - PlatformLogger('wlsdeploy.validate').logger.addHandler(self._summary_handler) + self._validate_logger = PlatformLogger('wlsdeploy.validate') + self._validate_logger.logger.addHandler(self._summary_handler) def tearDown(self): # remove summary handler for next test suite PlatformLogger('wlsdeploy.validate').logger.removeHandler(self._summary_handler) + WLSDeployLogEndHandler.clearHandlers() + + def testLogHandlerConfiguration(self): + _method_name = 'testLogHandlerConfiguration' + + self.assertNotEqual(self._summary_handler, None, 'self._summary_handler was None') + handlers = self._validate_logger.logger.getHandlers() + self.assertNotEqual(handlers, None, 'getHandlers() returned None') + self.assertNotEqual(len(handlers), 0, 'getHandlers() returned an empty list') + + found_summary_handler = False + for handler in handlers: + if handler.getClass().getName() == "oracle.weblogic.deploy.logging.SummaryHandler": + found_summary_handler = True + break + self.assertEquals(found_summary_handler, True, "Failed to find summary handler") + + handlers = WLSDeployLogEndHandler.getEndHandlers() + self.assertNotEqual(handlers, None, 'getEndHandlers() returned None') + self.assertNotEqual(len(handlers), 0, 'getEndHandlers() returned an empty list') + self.assertEqual(len(handlers), 1, 'getEndHandlers() returned a list with ' + str(len(handlers)) + ' handlers') def testCompareModelFull(self): _method_name = 'testCompareModelFull' @@ -231,6 +254,7 @@ def testCompareModelInvalidModel(self): shutil.rmtree(_temp_dir) os.mkdir(_temp_dir) + mw_home = os.environ['MW_HOME'] args_map = { '-oracle_home': mw_home, diff --git a/core/src/test/python/validation_test.py b/core/src/test/python/validation_test.py index 343c5c4e85..f837552810 100644 --- a/core/src/test/python/validation_test.py +++ b/core/src/test/python/validation_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) 2017, 2021, Oracle Corporation and/or its affiliates. +Copyright (c) 2017, 2022, Oracle Corporation and/or its affiliates. Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. """ import unittest @@ -7,6 +7,7 @@ from java.util.logging import Level from oracle.weblogic.deploy.logging import SummaryHandler +from oracle.weblogic.deploy.logging import WLSDeployLogEndHandler from wlsdeploy.logging.platform_logger import PlatformLogger from wlsdeploy.util.weblogic_helper import WebLogicHelper @@ -54,6 +55,7 @@ def setUp(self): def tearDown(self): # remove summary handler for next test suite self._logger.logger.removeHandler(self._summary_handler) + WLSDeployLogEndHandler.clearHandlers() # Clean up temporary WDT custom configuration environment variables # and model persistence files @@ -170,7 +172,7 @@ def testWLSRolesValidation(self): wlsroles_validator = wlsroles_helper.validator(wlsroles_dict, self._logger) wlsroles_validator.validate_roles() - handler = SummaryHandler.findInstance() + handler = self._summary_handler self.assertNotEqual(handler, None, "Summary handler is not present") # Verify only warnings resulted diff --git a/installer/src/main/bin/shared.cmd b/installer/src/main/bin/shared.cmd index 3e59219bd6..10f09e3d72 100644 --- a/installer/src/main/bin/shared.cmd +++ b/installer/src/main/bin/shared.cmd @@ -197,8 +197,7 @@ GOTO :EOF @REM set up logger configuration, see WLSDeployLoggingConfig.java - SET LOG_CONFIG_CLASS=oracle.weblogic.deploy.logging.WLSDeployCustomizeLoggingConfig - SET WLSDEPLOY_LOG_HANDLER=oracle.weblogic.deploy.logging.SummaryHandler + SET LOG_CONFIG_CLASS=oracle.weblogic.deploy.logging.WLSDeployLoggingConfig IF NOT DEFINED WLSDEPLOY_LOG_PROPERTIES ( SET WLSDEPLOY_LOG_PROPERTIES=%WLSDEPLOY_HOME%\etc\logging.properties @@ -206,9 +205,6 @@ GOTO :EOF IF NOT DEFINED WLSDEPLOY_LOG_DIRECTORY ( SET WLSDEPLOY_LOG_DIRECTORY=%WLSDEPLOY_HOME%\logs ) - IF NOT DEFINED WLSDEPLOY_LOG_HANDLERS ( - SET WLSDEPLOY_LOG_HANDLERS=%WLSDEPLOY_LOG_HANDLER% - ) GOTO :EOF :runWlst diff --git a/installer/src/main/bin/shared.sh b/installer/src/main/bin/shared.sh index 90b8922bc0..e540b00d83 100644 --- a/installer/src/main/bin/shared.sh +++ b/installer/src/main/bin/shared.sh @@ -160,8 +160,7 @@ variableSetup() { # set up logger configuration, see WLSDeployLoggingConfig.java - LOG_CONFIG_CLASS=oracle.weblogic.deploy.logging.WLSDeployCustomizeLoggingConfig - WLSDEPLOY_LOG_HANDLER=oracle.weblogic.deploy.logging.SummaryHandler + LOG_CONFIG_CLASS=oracle.weblogic.deploy.logging.WLSDeployLoggingConfig if [ -z "${WLSDEPLOY_LOG_PROPERTIES}" ]; then WLSDEPLOY_LOG_PROPERTIES="${WLSDEPLOY_HOME}/etc/logging.properties"; export WLSDEPLOY_LOG_PROPERTIES @@ -170,10 +169,6 @@ variableSetup() { if [ -z "${WLSDEPLOY_LOG_DIRECTORY}" ]; then WLSDEPLOY_LOG_DIRECTORY="${WLSDEPLOY_HOME}/logs"; export WLSDEPLOY_LOG_DIRECTORY fi - - if [ -z "${WLSDEPLOY_LOG_HANDLERS}" ]; then - WLSDEPLOY_LOG_HANDLERS=${WLSDEPLOY_LOG_HANDLER}; export WLSDEPLOY_LOG_HANDLERS - fi } runWlst() {