Java Code Examples for org.apache.logging.log4j.status.StatusLogger

The following examples show how to use org.apache.logging.log4j.status.StatusLogger. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: teku   Author: PegaSysEng   File: LoggingConfigurator.java    License: Apache License 2.0 6 votes vote down vote up
private static void displayProgrammaticLoggingConfiguration() {
  switch (DESTINATION) {
    case CONSOLE:
      StatusLogger.getLogger().info("Configuring logging for destination: console");
      break;
    case FILE:
      StatusLogger.getLogger().info("Configuring logging for destination: file");
      StatusLogger.getLogger().info("Logging file location: {}", FILE);
      break;
    default:
      // fall through
    case DEFAULT_BOTH:
      // fall through
    case BOTH:
      StatusLogger.getLogger().info("Configuring logging for destination: console and file");
      StatusLogger.getLogger().info("Logging file location: {}", FILE);
      break;
  }

  StatusLogger.getLogger().info("Logging includes events: {}", INCLUDE_EVENTS);
  StatusLogger.getLogger()
      .info("Logging includes validator duties: {}", INCLUDE_VALIDATOR_DUTIES);
  StatusLogger.getLogger().info("Logging includes color: {}", COLOR);
}
 
Example #2
Source Project: teku   Author: PegaSysEng   File: AdditionalProgrammaticConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Configuration reconfigure() {
  final Configuration refreshedParent = super.reconfigure();

  if (refreshedParent != null
      && AbstractConfiguration.class.isAssignableFrom(refreshedParent.getClass())) {

    try {
      final AdditionalProgrammaticConfiguration refreshed =
          new AdditionalProgrammaticConfiguration(
              refreshedParent.getLoggerContext(),
              refreshedParent.getConfigurationSource().resetInputStream());
      LoggingConfigurator.addLoggersProgrammatically(refreshed);
      return refreshed;
    } catch (final IOException e) {
      StatusLogger.getLogger().error("Failed to reload the Log4j2 Xml configuration file", e);
    }
  }

  StatusLogger.getLogger().warn("Cannot programmatically reconfigure loggers");
  return refreshedParent;
}
 
Example #3
Source Project: logging-log4j2   Author: apache   File: JdbcAppenderBenchmark.java    License: Apache License 2.0 6 votes vote down vote up
@Setup
public void setup() throws Exception {
    connectionHSQLDB = getConnectionHSQLDB();
    connectionH2 = getConnectionH2();
    createTable(connectionHSQLDB, toCreateTableSqlStringHQLDB("fmLogEntry"));
    createTable(connectionH2, toCreateTableSqlStringH2("fmLogEntry"));

    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "log4j2-jdbc-appender.xml");
    final LoggerContext context = LoggerContext.getContext(false);
    if (context.getConfiguration() instanceof DefaultConfiguration) {
        context.reconfigure();
    }
    StatusLogger.getLogger().reset();
    loggerH2 = LogManager.getLogger("H2Logger");
    loggerHSQLDB = LogManager.getLogger("HSQLDBLogger");
}
 
Example #4
Source Project: logging-log4j2   Author: apache   File: AbstractActionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testErrorsAreLoggedToStatusLogger() {
    StatusLogger statusLogger = StatusLogger.getLogger();
    statusLogger.clear();
    new AbstractAction() {
        @Override
        public boolean execute() {
            throw new AssertionError();
        }
    }.run();
    List<StatusData> statusDataList = statusLogger.getStatusData();
    assertEquals(1, statusDataList.size());
    StatusData statusData = statusDataList.get(0);
    assertEquals(Level.WARN, statusData.getLevel());
    String formattedMessage = statusData.getFormattedStatus();
    assertTrue(formattedMessage.contains("Exception reported by action"));
}
 
Example #5
Source Project: logging-log4j2   Author: apache   File: AbstractLoggerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMessageThrows() {
    final ThrowableExpectingLogger logger = new ThrowableExpectingLogger(false);
    logger.error(new TestMessage(new TestMessage.FormattedMessageSupplier() {
        @Override
        public String getFormattedMessage() {
            throw new IllegalStateException("Oops!");
        }
    }, "Message Format"));
    List<StatusData> statusDatalist = StatusLogger.getLogger().getStatusData();
    StatusData mostRecent = statusDatalist.get(statusDatalist.size() - 1);
    assertEquals(Level.WARN, mostRecent.getLevel());
    assertThat(mostRecent.getFormattedStatus(), containsString(
            "org.apache.logging.log4j.spi.AbstractLogger caught " +
                    "java.lang.IllegalStateException logging TestMessage: Message Format"));
}
 
Example #6
Source Project: logging-log4j2   Author: apache   File: AbstractLoggerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMessageThrowsAndNullFormat() {
    final ThrowableExpectingLogger logger = new ThrowableExpectingLogger(false);
    logger.error(new TestMessage(new TestMessage.FormattedMessageSupplier() {
        @Override
        public String getFormattedMessage() {
            throw new IllegalStateException("Oops!");
        }
    }, null /* format */));
    List<StatusData> statusDatalist = StatusLogger.getLogger().getStatusData();
    StatusData mostRecent = statusDatalist.get(statusDatalist.size() - 1);
    assertEquals(Level.WARN, mostRecent.getLevel());
    assertThat(mostRecent.getFormattedStatus(), containsString(
            "org.apache.logging.log4j.spi.AbstractLogger caught " +
                    "java.lang.IllegalStateException logging TestMessage: "));
}
 
Example #7
Source Project: logging-log4j2   Author: apache   File: PoolableConnectionFactoryConfig.java    License: Apache License 2.0 6 votes vote down vote up
public void init(final PoolableConnectionFactory poolableConnectionFactory) {
    if (poolableConnectionFactory != null) {
        StatusLogger.getLogger().debug("Initializing PoolableConnectionFactory {} with {}",
                poolableConnectionFactory, this);
        poolableConnectionFactory.setCacheState(cacheState);
        poolableConnectionFactory.setConnectionInitSql(connectionInitSqls);
        poolableConnectionFactory.setDefaultAutoCommit(defaultAutoCommit);
        poolableConnectionFactory.setDefaultCatalog(defaultCatalog);
        poolableConnectionFactory.setDefaultQueryTimeout(defaultQueryTimeoutSeconds);
        poolableConnectionFactory.setDefaultReadOnly(defaultReadOnly);
        poolableConnectionFactory.setDefaultTransactionIsolation(defaultTransactionIsolation);
        poolableConnectionFactory.setDisconnectionSqlCodes(disconnectionSqlCodes);
        poolableConnectionFactory.setEnableAutoCommitOnReturn(autoCommitOnReturn);
        poolableConnectionFactory.setFastFailValidation(fastFailValidation);
        poolableConnectionFactory.setMaxConnLifetimeMillis(maxConnLifetimeMillis);
        poolableConnectionFactory.setMaxOpenPreparedStatements(maxOpenPreparedStatements);
        poolableConnectionFactory.setPoolStatements(poolStatements);
        poolableConnectionFactory.setRollbackOnReturn(rollbackOnReturn);
        poolableConnectionFactory.setValidationQuery(validationQuery);
        poolableConnectionFactory.setValidationQueryTimeout(validationQueryTimeoutSeconds);
    }

}
 
Example #8
Source Project: logging-log4j2   Author: apache   File: CsvLogEventLayout.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String toSerializable(final LogEvent event) {
    final StringBuilder buffer = getStringBuilder();
    final CSVFormat format = getFormat();
    try {
        format.print(event.getNanoTime(), buffer, true);
        format.print(event.getTimeMillis(), buffer, false);
        format.print(event.getLevel(), buffer, false);
        format.print(event.getThreadId(), buffer, false);
        format.print(event.getThreadName(), buffer, false);
        format.print(event.getThreadPriority(), buffer, false);
        format.print(event.getMessage().getFormattedMessage(), buffer, false);
        format.print(event.getLoggerFqcn(), buffer, false);
        format.print(event.getLoggerName(), buffer, false);
        format.print(event.getMarker(), buffer, false);
        format.print(event.getThrownProxy(), buffer, false);
        format.print(event.getSource(), buffer, false);
        format.print(event.getContextData(), buffer, false);
        format.print(event.getContextStack(), buffer, false);
        format.println(buffer);
        return buffer.toString();
    } catch (final IOException e) {
        StatusLogger.getLogger().error(event.toString(), e);
        return format.getCommentMarker() + " " + e;
    }
}
 
Example #9
Source Project: logging-log4j2   Author: apache   File: LogEventAdapter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the result of {@code ManagementFactory.getRuntimeMXBean().getStartTime()},
 * or the current system time if JMX is not available.
 */
private static long initStartTime() {
    // We'd like to call ManagementFactory.getRuntimeMXBean().getStartTime(),
    // but Google App Engine throws a java.lang.NoClassDefFoundError
    // "java.lang.management.ManagementFactory is a restricted class".
    // The reflection is necessary because without it, Google App Engine
    // will refuse to initialize this class.
    try {
        final Class<?> factoryClass = Loader.loadSystemClass("java.lang.management.ManagementFactory");
        final Method getRuntimeMXBean = factoryClass.getMethod("getRuntimeMXBean");
        final Object runtimeMXBean = getRuntimeMXBean.invoke(null);

        final Class<?> runtimeMXBeanClass = Loader.loadSystemClass("java.lang.management.RuntimeMXBean");
        final Method getStartTime = runtimeMXBeanClass.getMethod("getStartTime");
        return (Long) getStartTime.invoke(runtimeMXBean);
    } catch (final Throwable t) {
        StatusLogger.getLogger().error("Unable to call ManagementFactory.getRuntimeMXBean().getStartTime(), "
                + "using system time for OnStartupTriggeringPolicy", t);
        // We have little option but to declare "now" as the beginning of time.
        return System.currentTimeMillis();
    }
}
 
Example #10
Source Project: logging-log4j2   Author: apache   File: LogEventAdapter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the result of {@code ManagementFactory.getRuntimeMXBean().getStartTime()},
 * or the current system time if JMX is not available.
 */
private static long initStartTime() {
    // We'd like to call ManagementFactory.getRuntimeMXBean().getStartTime(),
    // but Google App Engine throws a java.lang.NoClassDefFoundError
    // "java.lang.management.ManagementFactory is a restricted class".
    // The reflection is necessary because without it, Google App Engine
    // will refuse to initialize this class.
    try {
        final Class<?> factoryClass = Loader.loadSystemClass("java.lang.management.ManagementFactory");
        final Method getRuntimeMXBean = factoryClass.getMethod("getRuntimeMXBean");
        final Object runtimeMXBean = getRuntimeMXBean.invoke(null);

        final Class<?> runtimeMXBeanClass = Loader.loadSystemClass("java.lang.management.RuntimeMXBean");
        final Method getStartTime = runtimeMXBeanClass.getMethod("getStartTime");
        return (Long) getStartTime.invoke(runtimeMXBean);
    } catch (final Throwable t) {
        StatusLogger.getLogger().error("Unable to call ManagementFactory.getRuntimeMXBean().getStartTime(), "
            + "using system time for OnStartupTriggeringPolicy", t);
        // We have little option but to declare "now" as the beginning of time.
        return System.currentTimeMillis();
    }
}
 
Example #11
Source Project: logging-log4j2   Author: apache   File: JmsManager.java    License: Apache License 2.0 6 votes vote down vote up
private boolean closeConnection() {
    if (connection == null) {
        return true;
    }
    final Connection temp = connection;
    connection = null;
    try {
        temp.close();
        return true;
    } catch (final JMSException e) {
        StatusLogger.getLogger().debug(
                "Caught exception closing JMS Connection: {} ({}); continuing JMS manager shutdown",
                e.getLocalizedMessage(), temp, e);
        return false;
    }
}
 
Example #12
Source Project: logging-log4j2   Author: apache   File: JmsManager.java    License: Apache License 2.0 6 votes vote down vote up
private boolean closeMessageProducer() {
    if (messageProducer == null) {
        return true;
    }
    final MessageProducer temp = messageProducer;
    messageProducer = null;
    try {
        temp.close();
        return true;
    } catch (final JMSException e) {
        StatusLogger.getLogger().debug(
                "Caught exception closing JMS MessageProducer: {} ({}); continuing JMS manager shutdown",
                e.getLocalizedMessage(), temp, e);
        return false;
    }
}
 
Example #13
Source Project: logging-log4j2   Author: apache   File: JmsManager.java    License: Apache License 2.0 6 votes vote down vote up
private boolean closeSession() {
    if (session == null) {
        return true;
    }
    final Session temp = session;
    session = null;
    try {
        temp.close();
        return true;
    } catch (final JMSException e) {
        StatusLogger.getLogger().debug(
                "Caught exception closing JMS Session: {} ({}); continuing JMS manager shutdown",
                e.getLocalizedMessage(), temp, e);
        return false;
    }
}
 
Example #14
Source Project: logging-log4j2   Author: apache   File: AbstractJpaAppenderTest.java    License: Apache License 2.0 6 votes vote down vote up
public void tearDown() throws SQLException {
    final LoggerContext context = LoggerContext.getContext(false);
    try {
        String appenderName = "databaseAppender";
        final Appender appender = context.getConfiguration().getAppender(appenderName);
        assertNotNull("The appender '" + appenderName + "' should not be null.", appender);
        assertTrue("The appender should be a JpaAppender.", appender instanceof JpaAppender);
        ((JpaAppender) appender).getManager().close();
    } finally {
        System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
        PropertiesUtil.getProperties().reload();
        context.reconfigure();
        StatusLogger.getLogger().reset();

        try (Statement statement = this.connection.createStatement();) {
            statement.execute("SHUTDOWN");
        }

        this.connection.close();
    }
}
 
Example #15
Source Project: logging-log4j2   Author: apache   File: MessagePatternConverter.java    License: Apache License 2.0 6 votes vote down vote up
private TextRenderer loadMessageRenderer(final String[] options) {
    if (options != null) {
        for (final String option : options) {
            switch (option.toUpperCase(Locale.ROOT)) {
            case "ANSI":
                if (Loader.isJansiAvailable()) {
                    return new JAnsiTextRenderer(options, JAnsiTextRenderer.DefaultMessageStyleMap);
                }
                StatusLogger.getLogger()
                        .warn("You requested ANSI message rendering but JANSI is not on the classpath.");
                return null;
            case "HTML":
                return new HtmlTextRenderer(options);
            }
        }
    }
    return null;
}
 
Example #16
Source Project: logging-log4j2   Author: apache   File: ReliabilityStrategyFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new {@code ReliabilityStrategy} instance based on the value of system property
 * {@code log4j.ReliabilityStrategy}. If not value was specified this method returns a new
 * {@code AwaitUnconditionallyReliabilityStrategy}.
 * <p>
 * Valid values for this system property are {@code "AwaitUnconditionally"} (use
 * {@code AwaitUnconditionallyReliabilityStrategy}), {@code "Locking"} (use {@code LockingReliabilityStrategy}) and
 * {@code "AwaitCompletion"} (use the default {@code AwaitCompletionReliabilityStrategy}).
 * <p>
 * Users may also use this system property to specify the fully qualified class name of a class that implements the
 * {@code ReliabilityStrategy} and has a constructor that accepts a single {@code LoggerConfig} argument.
 * 
 * @param loggerConfig the LoggerConfig the resulting {@code ReliabilityStrategy} is associated with
 * @return a ReliabilityStrategy that helps the specified LoggerConfig to log events reliably during or after a
 *         configuration change
 */
public static ReliabilityStrategy getReliabilityStrategy(final LoggerConfig loggerConfig) {

    final String strategy = PropertiesUtil.getProperties().getStringProperty("log4j.ReliabilityStrategy",
            "AwaitCompletion");
    if ("AwaitCompletion".equals(strategy)) {
        return new AwaitCompletionReliabilityStrategy(loggerConfig);
    }
    if ("AwaitUnconditionally".equals(strategy)) {
        return new AwaitUnconditionallyReliabilityStrategy(loggerConfig);
    }
    if ("Locking".equals(strategy)) {
        return new LockingReliabilityStrategy(loggerConfig);
    }
    try {
        final Class<? extends ReliabilityStrategy> cls = Loader.loadClass(strategy).asSubclass(
            ReliabilityStrategy.class);
        return cls.getConstructor(LoggerConfig.class).newInstance(loggerConfig);
    } catch (final Exception dynamicFailed) {
        StatusLogger.getLogger().warn(
                "Could not create ReliabilityStrategy for '{}', using default AwaitCompletionReliabilityStrategy: {}", strategy, dynamicFailed);
        return new AwaitCompletionReliabilityStrategy(loggerConfig);
    }
}
 
Example #17
Source Project: logging-log4j2   Author: apache   File: AbstractActionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRuntimeExceptionsAreLoggedToStatusLogger() {
    StatusLogger statusLogger = StatusLogger.getLogger();
    statusLogger.clear();
    new AbstractAction() {
        @Override
        public boolean execute() {
            throw new IllegalStateException();
        }
    }.run();
    List<StatusData> statusDataList = statusLogger.getStatusData();
    assertEquals(1, statusDataList.size());
    StatusData statusData = statusDataList.get(0);
    assertEquals(Level.WARN, statusData.getLevel());
    String formattedMessage = statusData.getFormattedStatus();
    assertTrue(formattedMessage.contains("Exception reported by action"));
}
 
Example #18
Source Project: logging-log4j2   Author: apache   File: OnStartupTriggeringPolicy.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the result of {@code ManagementFactory.getRuntimeMXBean().getStartTime()},
 * or the current system time if JMX is not available.
 */
private static long initStartTime() {
    // LOG4J2-379:
    // We'd like to call ManagementFactory.getRuntimeMXBean().getStartTime(),
    // but Google App Engine throws a java.lang.NoClassDefFoundError
    // "java.lang.management.ManagementFactory is a restricted class".
    // The reflection is necessary because without it, Google App Engine
    // will refuse to initialize this class.
    try {
        final Class<?> factoryClass = Loader.loadSystemClass("java.lang.management.ManagementFactory");
        final Method getRuntimeMXBean = factoryClass.getMethod("getRuntimeMXBean");
        final Object runtimeMXBean = getRuntimeMXBean.invoke(null);

        final Class<?> runtimeMXBeanClass = Loader.loadSystemClass("java.lang.management.RuntimeMXBean");
        final Method getStartTime = runtimeMXBeanClass.getMethod("getStartTime");
        final Long result = (Long) getStartTime.invoke(runtimeMXBean);

        return result;
    } catch (final Throwable t) {
        StatusLogger.getLogger().error("Unable to call ManagementFactory.getRuntimeMXBean().getStartTime(), "
                + "using system time for OnStartupTriggeringPolicy", t);
        // We have little option but to declare "now" as the beginning of time.
        return System.currentTimeMillis();
    }
}
 
Example #19
Source Project: logging-log4j2   Author: apache   File: GelfLayout.java    License: Apache License 2.0 6 votes vote down vote up
private byte[] compress(final byte[] bytes) {
    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream(compressionThreshold / 8);
        try (final DeflaterOutputStream stream = compressionType.createDeflaterOutputStream(baos)) {
            if (stream == null) {
                return bytes;
            }
            stream.write(bytes);
            stream.finish();
        }
        return baos.toByteArray();
    } catch (final IOException e) {
        StatusLogger.getLogger().error(e);
        return bytes;
    }
}
 
Example #20
Source Project: logging-log4j2   Author: apache   File: RollingAppenderCronOnceADayTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Exception {
  final Path src = FileSystems.getDefault().getPath(TARGET_TEST_CLASSES, CONFIG);
  String content = new String(Files.readAllBytes(src), UTF_8);
  final Calendar cal = Calendar.getInstance();
  cal.add(Calendar.SECOND, CRON_DELAY);
  remainingTime = cal.getTimeInMillis() - System.currentTimeMillis();
  cronExpression =  String.format("%d %d %d * * ?",
      cal.get(Calendar.SECOND),
      cal.get(Calendar.MINUTE),
      cal.get(Calendar.HOUR_OF_DAY));
  content = content.replace("@[email protected]", cronExpression);
  Files.write(FileSystems.getDefault()
        .getPath(TARGET_TEST_CLASSES, CONFIG_TARGET), content.getBytes(UTF_8));
  StatusLogger.getLogger().debug("Cron expression will be " + cronExpression + " in " + remainingTime + "ms");
}
 
Example #21
Source Project: logging-log4j2   Author: apache   File: AbstractActionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExceptionsAreLoggedToStatusLogger() {
    StatusLogger statusLogger = StatusLogger.getLogger();
    statusLogger.clear();
    new TestAction().run();
    List<StatusData> statusDataList = statusLogger.getStatusData();
    assertEquals(1, statusDataList.size());
    StatusData statusData = statusDataList.get(0);
    assertEquals(Level.WARN, statusData.getLevel());
    String formattedMessage = statusData.getFormattedStatus();
    assertTrue(formattedMessage, formattedMessage.contains("Exception reported by action 'class org.apache."
            + "logging.log4j.core.appender.rolling.action.AbstractActionTest$TestAction' java.io.IOException: "
            + "failed" + System.lineSeparator()
            + "\tat org.apache.logging.log4j.core.appender.rolling.action.AbstractActionTest"
            + "$TestAction.execute(AbstractActionTest.java:"));
}
 
Example #22
Source Project: ecs-logging-java   Author: elastic   File: ObjectMessageJacksonSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void formatTo(StringBuilder buffer, ObjectMessage objectMessage) {
    try {
        objectMapper.writeValue(new StringBuilderWriter(buffer), objectMessage.getParameter());
    } catch (IOException e) {
        StatusLogger.getLogger().catching(e);
        objectMessage.formatTo(buffer);
    }
}
 
Example #23
static void asyncLoggerConfigRecursiveTest(final Logger logger,
                                           final Unlocker unlocker,
                                           final BlockingAppender blockingAppender,
                                           final QueueFullAbstractTest factory) {
    for (int i = 0; i < 1; i++) {
        TRACE("Test logging message " + i  + ". Remaining capacity=" + asyncRemainingCapacity(logger));
        TRACE("Test decrementing unlocker countdown latch. Count=" + unlocker.countDownLatch.getCount());
        unlocker.countDownLatch.countDown();
        final DomainObject obj = factory.new DomainObject(129);
        logger.info("logging naughty object #{} {}", i, obj);
    }
    TRACE("Before stop() blockingAppender.logEvents.count=" + blockingAppender.logEvents.size());
    //CoreLoggerContexts.stopLoggerContext(false); // stop async thread
    while (blockingAppender.logEvents.size() < 130) { Thread.yield(); }
    TRACE("After  stop() blockingAppender.logEvents.count=" + blockingAppender.logEvents.size());

    final Stack<String> actual = transform(blockingAppender.logEvents);
    assertEquals("Logging in toString() #0", actual.pop());
    List<StatusData> statusDataList = StatusLogger.getLogger().getStatusData();
    assertEquals("Jumped the queue: queue full",
            "Logging in toString() #128", actual.pop());
    StatusData mostRecentStatusData = statusDataList.get(statusDataList.size() - 1);
    assertEquals("Expected warn level status message", Level.WARN, mostRecentStatusData.getLevel());
    assertThat(mostRecentStatusData.getFormattedStatus(), containsString(
            "Log4j2 logged an event out of order to prevent deadlock caused by domain " +
                    "objects logging from their toString method when the async queue is full"));

    for (int i = 1; i < 128; i++) {
        assertEquals("First batch", "Logging in toString() #" + i, actual.pop());
    }
    assertEquals("logging naughty object #0 Who's bad?!", actual.pop());
    assertTrue(actual.isEmpty());
}
 
Example #24
Source Project: teku   Author: PegaSysEng   File: LoggingConfigurator.java    License: Apache License 2.0 5 votes vote down vote up
private static void displayUnknownDestinationConfigured() {
  StatusLogger.getLogger()
      .warn(
          "Unknown logging destination: {}, applying default: {}",
          DESTINATION,
          LoggingDestination.BOTH);
}
 
Example #25
Source Project: openwebbeans-meecrowave   Author: apache   File: Log4j2Logger.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setLevel(final Level newLevel) throws SecurityException {
    if (org.apache.logging.log4j.core.Logger.class.isInstance(log)) {
        org.apache.logging.log4j.core.Logger.class.cast(log).setLevel(TO_LOG4J.get(newLevel));
    } else if (StatusLogger.class.isInstance(log)) {
        StatusLogger.class.cast(log).setLevel(TO_LOG4J.get(newLevel));
    } else if (SimpleLogger.class.isInstance(log)) {
        SimpleLogger.class.cast(log).setLevel(TO_LOG4J.get(newLevel));
    } // else ExtendedLoggerWrapper: ignore for now. we could do reflection if we need it
}
 
Example #26
Source Project: crate   Author: crate   File: LogConfigurator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Configure logging reading from any log4j2.properties found in the config directory and its
 * subdirectories from the specified environment. Will also configure logging to point the logs
 * directory from the specified environment.
 *
 * @param environment the environment for reading configs and the logs path
 * @throws IOException   if there is an issue readings any log4j2.properties in the config
 *                       directory
 * @throws UserException if there are no log4j2.properties in the specified configs path
 */
public static void configure(final Environment environment) throws IOException, UserException {
    Objects.requireNonNull(environment);
    try {
        // we are about to configure logging, check that the status logger did not log any error-level messages
        checkErrorListener();
    } finally {
        // whether or not the error listener check failed we can remove the listener now
        StatusLogger.getLogger().removeListener(ERROR_LISTENER);
    }
    configure(environment.settings(), environment.configFile(), environment.logsFile());
}
 
Example #27
Source Project: crate   Author: crate   File: ESTestCase.java    License: Apache License 2.0 5 votes vote down vote up
protected static void checkStaticState(boolean afterClass) throws Exception {
    if (afterClass) {
        MockPageCacheRecycler.ensureAllPagesAreReleased();
    }
    MockBigArrays.ensureAllArraysAreReleased();

    // ensure no one changed the status logger level on us
    assertThat(StatusLogger.getLogger().getLevel(), equalTo(Level.WARN));
    synchronized (statusData) {
        try {
            // ensure that there are no status logger messages which would indicate a problem with our Log4j usage; we map the
            // StatusData instances to Strings as otherwise their toString output is useless
            assertThat(
                statusData.stream().map(status -> status.getMessage().getFormattedMessage()).collect(Collectors.toList()),
                empty());
        } finally {
            // we clear the list so that status data from other tests do not interfere with tests within the same JVM
            statusData.clear();
        }
    }
    synchronized (nettyLoggedLeaks) {
        try {
            assertThat(nettyLoggedLeaks, empty());
        } finally {
            nettyLoggedLeaks.clear();
        }
    }
}
 
Example #28
Source Project: logging-log4j2   Author: apache   File: JpaAppenderBenchmark.java    License: Apache License 2.0 5 votes vote down vote up
@Setup
public void setup() throws Exception {
    connectionHSQLDB = getConnectionHSQLDB();
    connectionH2 = getConnectionH2();

    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "log4j2-jpa-appender.xml");
    final LoggerContext context = LoggerContext.getContext(false);
    if (context.getConfiguration() instanceof DefaultConfiguration) {
        context.reconfigure();
    }
    StatusLogger.getLogger().reset();
    loggerH2 = LogManager.getLogger("H2Logger");
    loggerHSQLDB = LogManager.getLogger("HSQLDBLogger");
}
 
Example #29
Source Project: logging-log4j2   Author: apache   File: LocalizedMessage.java    License: Apache License 2.0 5 votes vote down vote up
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    formattedMessage = in.readUTF();
    key = in.readUTF();
    baseName = in.readUTF();
    in.readInt();
    stringArgs = (String[]) in.readObject();
    logger = StatusLogger.getLogger();
    resourceBundle = null;
    argArray = null;
}
 
Example #30
Source Project: logging-log4j2   Author: apache   File: AbstractLogger.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks that the message factory a logger was created with is the same as the given messageFactory. If they are
 * different log a warning to the {@linkplain StatusLogger}. A null MessageFactory translates to the default
 * MessageFactory {@link #DEFAULT_MESSAGE_FACTORY_CLASS}.
 *
 * @param logger The logger to check
 * @param messageFactory The message factory to check.
 */
public static void checkMessageFactory(final ExtendedLogger logger, final MessageFactory messageFactory) {
    final String name = logger.getName();
    final MessageFactory loggerMessageFactory = logger.getMessageFactory();
    if (messageFactory != null && !loggerMessageFactory.equals(messageFactory)) {
        StatusLogger.getLogger().warn(
                "The Logger {} was created with the message factory {} and is now requested with the "
                        + "message factory {}, which may create log events with unexpected formatting.", name,
                loggerMessageFactory, messageFactory);
    } else if (messageFactory == null && !loggerMessageFactory.getClass().equals(DEFAULT_MESSAGE_FACTORY_CLASS)) {
        StatusLogger
                .getLogger()
                .warn("The Logger {} was created with the message factory {} and is now requested with a null "
                        + "message factory (defaults to {}), which may create log events with unexpected "
                        + "formatting.",
                        name, loggerMessageFactory, DEFAULT_MESSAGE_FACTORY_CLASS.getName());
    }
}