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

The following examples show how to use org.apache.logging.log4j.status.StatusLogger. 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 File: PoolableConnectionFactoryConfig.java    From logging-log4j2 with 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 #2
Source File: JdbcAppenderBenchmark.java    From logging-log4j2 with 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 #3
Source File: RollingAppenderCronOnceADayTest.java    From logging-log4j2 with 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("@CRON_EXPR@", 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 #4
Source File: AdditionalProgrammaticConfiguration.java    From teku with 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 #5
Source File: LoggingConfigurator.java    From teku with 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 #6
Source File: AbstractActionTest.java    From logging-log4j2 with 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 #7
Source File: AbstractActionTest.java    From logging-log4j2 with 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 #8
Source File: LogEventAdapter.java    From logging-log4j2 with 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 #9
Source File: AbstractLoggerTest.java    From logging-log4j2 with 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 #10
Source File: AbstractLoggerTest.java    From logging-log4j2 with 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 #11
Source File: CsvLogEventLayout.java    From logging-log4j2 with 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 #12
Source File: LogEventAdapter.java    From logging-log4j2 with 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 #13
Source File: JmsManager.java    From logging-log4j2 with 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 #14
Source File: JmsManager.java    From logging-log4j2 with 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 #15
Source File: JmsManager.java    From logging-log4j2 with 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 #16
Source File: AbstractJpaAppenderTest.java    From logging-log4j2 with 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 #17
Source File: MessagePatternConverter.java    From logging-log4j2 with 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 #18
Source File: GelfLayout.java    From logging-log4j2 with 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 #19
Source File: ReliabilityStrategyFactory.java    From logging-log4j2 with 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 #20
Source File: OnStartupTriggeringPolicy.java    From logging-log4j2 with 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 #21
Source File: AbstractActionTest.java    From logging-log4j2 with 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 #22
Source File: CustomLevelConfig.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a CustomLevelConfig object. This also defines the Level object with a call to
 * {@link Level#forName(String, int)}.
 * 
 * @param levelName name of the custom level.
 * @param intLevel the intLevel that determines where this level resides relative to the built-in levels
 * @return A CustomLevelConfig object.
 */
@PluginFactory
public static CustomLevelConfig createLevel(// @formatter:off
        @PluginAttribute("name") final String levelName,
        @PluginAttribute final int intLevel) {
    // @formatter:on

    StatusLogger.getLogger().debug("Creating CustomLevel(name='{}', intValue={})", levelName, intLevel);
    Level.forName(levelName, intLevel);
    return new CustomLevelConfig(levelName, intLevel);
}
 
Example #23
Source File: AwaitUnconditionallyReliabilityStrategy.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeStopConfiguration(final Configuration configuration) {
    // only sleep once per configuration stop
    if (loggerConfig == configuration.getRootLogger()) {
        try {
            Thread.sleep(SLEEP_MILLIS);
        } catch (final InterruptedException e) {
            StatusLogger.getLogger().warn("Sleep before stop configuration was interrupted.");
        }
    }
}
 
Example #24
Source File: OnStartupTriggeringPolicy.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Provide the RollingFileManager to the policy.
 * @param manager The RollingFileManager.
 */
@Override
public void initialize(final RollingFileManager manager) {
    if (manager.getFileTime() < JVM_START_TIME && manager.getFileSize() >= minSize) {
        StatusLogger.getLogger().debug("Initiating rollover at startup");
        if (minSize == 0) {
            manager.setRenameEmptyFiles(true);
        }
        manager.skipFooter(true);
        manager.rollover();
        manager.skipFooter(false);
    }
}
 
Example #25
Source File: AbstractJpaAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public void setUp(final String configFileName) throws SQLException {
    this.connection = this.setUpConnection();

    final String resource = "org/apache/logging/log4j/jpa/appender/" + configFileName;
    assertNotNull(getClass().getClassLoader().getResource(resource));
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
            resource);
    PropertiesUtil.getProperties().reload();
    final LoggerContext context = LoggerContext.getContext(false);
    if (context.getConfiguration() instanceof DefaultConfiguration) {
        context.reconfigure();
    }
    StatusLogger.getLogger().reset();
}
 
Example #26
Source File: Log4jServletContainerInitializer.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void onStartup(final Set<Class<?>> classes, final ServletContext servletContext) throws ServletException {
    if (servletContext.getMajorVersion() > 2 && servletContext.getEffectiveMajorVersion() > 2 &&
            !"true".equalsIgnoreCase(servletContext.getInitParameter(
                    Log4jWebSupport.IS_LOG4J_AUTO_INITIALIZATION_DISABLED
            ))) {
        final Logger LOGGER = StatusLogger.getLogger();

        LOGGER.debug("Log4jServletContainerInitializer starting up Log4j in Servlet 3.0+ environment.");

        final FilterRegistration.Dynamic filter =
                servletContext.addFilter("log4jServletFilter", Log4jServletFilter.class);
        if (filter == null) {
            LOGGER.warn("WARNING: In a Servlet 3.0+ application, you should not define a " +
                "log4jServletFilter in web.xml. Log4j 2 normally does this for you automatically. Log4j 2 " +
                "web auto-initialization has been canceled.");
            return;
        }

        final Log4jWebLifeCycle initializer = WebLoggerContextUtils.getWebLifeCycle(servletContext);
        initializer.start();
        initializer.setLoggerContext(); // the application is just now starting to start up

        servletContext.addListener(new Log4jServletContextListener());

        filter.setAsyncSupported(true); // supporting async when the user isn't using async has no downsides
        filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");
    }
}
 
Example #27
Source File: LoggerContextRule.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public Statement apply(final Statement base, final Description description) {
    // Hack: Using -DEBUG as a JVM param sets a property called "EBUG"...
    if (System.getProperties().containsKey("EBUG")) {
        StatusLogger.getLogger().setLevel(Level.DEBUG);
    }
    testClassName = description.getClassName();
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            if (contextSelectorClass != null) {
                System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, contextSelectorClass.getName());
            }
            // TODO Consider instead of the above:
            // LogManager.setFactory(new Log4jContextFactory(LoaderUtil.newInstanceOf(contextSelectorClass)));
            System.setProperty(SYS_PROP_KEY_CLASS_NAME, description.getClassName());
            System.setProperty(SYS_PROP_KEY_DISPLAY_NAME, description.getDisplayName());
            loggerContext = Configurator.initialize(description.getDisplayName(),
                    description.getTestClass().getClassLoader(), configurationLocation);
            try {
                base.evaluate();
            } finally {
                if (!Configurator.shutdown(loggerContext, shutdownTimeout, shutdownTimeUnit)) {
                    StatusLogger.getLogger().error("Logger context {} did not shutdown completely after {} {}.",
                            loggerContext.getName(), shutdownTimeout, shutdownTimeUnit);
                }
                loggerContext = null;
                contextSelectorClass = null;
                StatusLogger.getLogger().reset();
                System.clearProperty(Constants.LOG4J_CONTEXT_SELECTOR);
                System.clearProperty(SYS_PROP_KEY_CLASS_NAME);
                System.clearProperty(SYS_PROP_KEY_DISPLAY_NAME);
            }
        }
    };

}
 
Example #28
Source File: ObjectMessageJacksonSerializer.java    From ecs-logging-java with 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 #29
Source File: RollingAppenderDirectWrite1906Test.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private String logFileNameError(String expected, String actual) {
    final List<StatusData> statusData = StatusLogger.getLogger().getStatusData();
    final StringBuilder sb = new StringBuilder();
    for (StatusData statusItem : statusData) {
        sb.append(statusItem.getFormattedStatus());
        sb.append("\n");
    }
    sb.append("Incorrect file name. Expected: ").append(expected).append(" Actual: ").append(actual);
    return sb.toString();
}
 
Example #30
Source File: Log4j2Logger.java    From openwebbeans-meecrowave with 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
}