类org.apache.logging.log4j.status.StatusLogger源码实例Demo

下面列出了怎么用org.apache.logging.log4j.status.StatusLogger的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: teku   文件: LoggingConfigurator.java
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);
}
 
@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;
}
 
源代码3 项目: logging-log4j2   文件: JdbcAppenderBenchmark.java
@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");
}
 
源代码4 项目: logging-log4j2   文件: AbstractActionTest.java
@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"));
}
 
源代码5 项目: logging-log4j2   文件: AbstractLoggerTest.java
@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"));
}
 
源代码6 项目: logging-log4j2   文件: AbstractLoggerTest.java
@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: "));
}
 
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);
    }

}
 
源代码8 项目: logging-log4j2   文件: CsvLogEventLayout.java
@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;
    }
}
 
源代码9 项目: logging-log4j2   文件: LogEventAdapter.java
/**
 * 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();
    }
}
 
源代码10 项目: logging-log4j2   文件: LogEventAdapter.java
/**
 * 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();
    }
}
 
源代码11 项目: logging-log4j2   文件: JmsManager.java
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;
    }
}
 
源代码12 项目: logging-log4j2   文件: JmsManager.java
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;
    }
}
 
源代码13 项目: logging-log4j2   文件: JmsManager.java
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;
    }
}
 
源代码14 项目: logging-log4j2   文件: AbstractJpaAppenderTest.java
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();
    }
}
 
源代码15 项目: logging-log4j2   文件: MessagePatternConverter.java
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;
}
 
/**
 * 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);
    }
}
 
源代码17 项目: logging-log4j2   文件: AbstractActionTest.java
@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"));
}
 
源代码18 项目: logging-log4j2   文件: OnStartupTriggeringPolicy.java
/**
 * 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();
    }
}
 
源代码19 项目: logging-log4j2   文件: GelfLayout.java
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;
    }
}
 
@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");
}
 
源代码21 项目: logging-log4j2   文件: AbstractActionTest.java
@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:"));
}
 
@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);
    }
}
 
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());
}
 
源代码24 项目: teku   文件: LoggingConfigurator.java
private static void displayUnknownDestinationConfigured() {
  StatusLogger.getLogger()
      .warn(
          "Unknown logging destination: {}, applying default: {}",
          DESTINATION,
          LoggingDestination.BOTH);
}
 
源代码25 项目: openwebbeans-meecrowave   文件: Log4j2Logger.java
@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
}
 
源代码26 项目: crate   文件: LogConfigurator.java
/**
 * 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());
}
 
源代码27 项目: crate   文件: ESTestCase.java
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();
        }
    }
}
 
源代码28 项目: logging-log4j2   文件: JpaAppenderBenchmark.java
@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");
}
 
源代码29 项目: logging-log4j2   文件: LocalizedMessage.java
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;
}
 
源代码30 项目: logging-log4j2   文件: AbstractLogger.java
/**
 * 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());
    }
}
 
 类所在包
 类方法
 同包方法