Java Code Examples for org.apache.logging.log4j.core.LoggerContext#stop()

The following examples show how to use org.apache.logging.log4j.core.LoggerContext#stop() . 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: CsvJsonParameterLayoutFileAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public void testNoNulCharacters(final String message, final String expected) throws IOException {
    @SuppressWarnings("resource")
    final LoggerContext loggerContext = loggerContextRule.getLoggerContext();
    final Logger logger = loggerContext.getLogger("com.example");
    logger.error("log:", message);
    loggerContext.stop();
    final File file = new File(FILE_PATH);
    final byte[] contents = FileUtils.readFileToByteArray(file);
    int count0s = 0;
    final StringBuilder sb = new StringBuilder();
    for (int i = 0; i < contents.length; i++) {
        final byte b = contents[i];
        if (b == 0) {
            sb.append(i);
            sb.append(", ");
            count0s++;
        }
    }
    Assert.assertEquals("File contains " + count0s + " 0x00 byte at indices " + sb, 0, count0s);
    final List<String> readLines = FileUtils.readLines(file, Charset.defaultCharset());
    final String actual = readLines.get(0);
    // Assert.assertTrue(actual, actual.contains(message));
    Assert.assertEquals(actual, expected, actual);
    Assert.assertEquals(1, readLines.size());
}
 
Example 2
Source File: ClassLoaderContextSelector.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public void shutdown(final String fqcn, final ClassLoader loader, final boolean currentContext,
                     final boolean allContexts) {
    LoggerContext ctx = null;
    if (currentContext) {
        ctx = ContextAnchor.THREAD_CONTEXT.get();
    } else if (loader != null) {
        ctx = findContext(loader);
    } else {
        final Class<?> clazz = StackLocatorUtil.getCallerClass(fqcn);
        if (clazz != null) {
            ctx = findContext(clazz.getClassLoader());
        }
        if (ctx == null) {
            ctx = ContextAnchor.THREAD_CONTEXT.get();
        }
    }
    if (ctx != null) {
        ctx.stop(DEFAULT_STOP_TIMEOUT, TimeUnit.MILLISECONDS);
    }
}
 
Example 3
Source File: JiraLog4j2_2134Test.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testRefresh() {
	Logger log = LogManager.getLogger(this.getClass());
	final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
	final Configuration config = ctx.getConfiguration();
	PatternLayout layout = PatternLayout.newBuilder()
	// @formatter:off
			.setPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN)
			.setConfiguration(config)
			.build();
	// @formatter:on
	Appender appender = FileAppender.newBuilder().setFileName("target/test.log").setLayout(layout)
			.setConfiguration(config).setBufferSize(4000).setName("File").build();
	// appender.start();
	config.addAppender(appender);
	AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
	AppenderRef[] refs = new AppenderRef[] { ref };
	LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "testlog4j2refresh", "true", refs,
			null, config, null);
	loggerConfig.addAppender(appender, null, null);
	config.addLogger("testlog4j2refresh", loggerConfig);
	ctx.stop();
	ctx.start(config);

	log.error("Info message");
}
 
Example 4
Source File: BundleContextSelector.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void shutdown(final String fqcn, final ClassLoader loader, final boolean currentContext,
                     final boolean allContexts) {
    LoggerContext ctx = null;
    Bundle bundle = null;
    if (currentContext) {
        ctx = ContextAnchor.THREAD_CONTEXT.get();
        ContextAnchor.THREAD_CONTEXT.remove();
    }
    if (ctx == null && loader instanceof BundleReference) {
        bundle = ((BundleReference) loader).getBundle();
        ctx = getLoggerContext(bundle);
        removeLoggerContext(ctx);
    }
    if (ctx == null) {
        final Class<?> callerClass = StackLocatorUtil.getCallerClass(fqcn);
        if (callerClass != null) {
            bundle = FrameworkUtil.getBundle(callerClass);
            ctx = getLoggerContext(FrameworkUtil.getBundle(callerClass));
            removeLoggerContext(ctx);
        }
    }
    if (ctx == null) {
        ctx = ContextAnchor.THREAD_CONTEXT.get();
        ContextAnchor.THREAD_CONTEXT.remove();
    }
    if (ctx != null) {
        ctx.stop(DEFAULT_STOP_TIMEOUT, TimeUnit.MILLISECONDS);
    }
    if (bundle != null && allContexts) {
        final Bundle[] bundles = bundle.getBundleContext().getBundles();
        for (final Bundle bdl : bundles) {
            ctx = getLoggerContext(bdl);
            if (ctx != null) {
                ctx.stop(DEFAULT_STOP_TIMEOUT, TimeUnit.MILLISECONDS);
            }
        }
    }
}
 
Example 5
Source File: JndiContextSelector.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void shutdown(String fqcn, ClassLoader loader, boolean currentContext, boolean allContexts) {
    LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get();
    if (ctx == null) {
        String loggingContextName = getContextName();
        if (loggingContextName != null) {
            ctx = CONTEXT_MAP.get(loggingContextName);
        }
    }
    if (ctx != null) {
        ctx.stop(DEFAULT_STOP_TIMEOUT, TimeUnit.MILLISECONDS);
    }
}
 
Example 6
Source File: JiraLog4j2_2134Test.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRefreshMinimalCodeStopStart() {
	Logger log = LogManager.getLogger(this.getClass());
	final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
	ctx.stop();
	ctx.start();

	log.error("Info message");
}
 
Example 7
Source File: JiraLog4j2_2134Test.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRefreshMinimalCodeStopStartConfig() {
	Logger log = LogManager.getLogger(this.getClass());
	final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
	final Configuration config = ctx.getConfiguration();
	ctx.stop();
	ctx.start(config);

	log.error("Info message");
}
 
Example 8
Source File: AdvertiserTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAdvertisementsRemovedOnConfigStop() {
    verifyExpectedEntriesAdvertised(InMemoryAdvertiser.getAdvertisedEntries());

    final LoggerContext ctx = LoggerContext.getContext();
    ctx.stop();

    final Map<Object, Map<String, String>> entries = InMemoryAdvertiser.getAdvertisedEntries();
    assertTrue("Entries found: " + entries, entries.isEmpty());

    //reconfigure for subsequent testing
    ctx.start();
}
 
Example 9
Source File: AdvertiserTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAdvertisementsAddedOnReconfigAfterStop() {
    verifyExpectedEntriesAdvertised(InMemoryAdvertiser.getAdvertisedEntries());

    final LoggerContext ctx = LoggerContext.getContext();
    ctx.stop();

    final Map<Object, Map<String, String>> entries = InMemoryAdvertiser.getAdvertisedEntries();
    assertTrue("Entries found: " + entries, entries.isEmpty());

    ctx.start();

    verifyExpectedEntriesAdvertised(InMemoryAdvertiser.getAdvertisedEntries());
}
 
Example 10
Source File: AsyncAppenderShutdownTimeoutTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 5000)
public void shutdownTest() throws Exception {
    final LoggerContext ctx = (LoggerContext)LogManager.getContext(false);
    final Logger logger = ctx.getLogger("Logger");
    logger.info("This is a test");
    ctx.stop();
}
 
Example 11
Source File: JiraLog4j2_2134Test.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testRefreshDeprecatedApis() {
	Logger log = LogManager.getLogger(this.getClass());
	final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
	final Configuration config = ctx.getConfiguration();
	PatternLayout layout = PatternLayout.newBuilder()
	        .setPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN)
	        .setPatternSelector(null)
	        .setConfiguration(config)
	        .setRegexReplacement(null)
	        .setCharset(null)
	        .setAlwaysWriteExceptions(false)
	        .setNoConsoleNoAnsi(false)
	        .setHeader(null)
	        .setFooter(null)
	        .build();
	// @formatter:off
	Appender appender = FileAppender.newBuilder()
	        .setFileName("target/test.log")
	        .setAppend(false)
	        .setLocking(false)
	        .setName("File")
	        .setImmediateFlush(true)
	        .setIgnoreExceptions(false)
	        .setBufferedIo(false)
	        .setBufferSize(4000)
	        .setLayout(layout)
	        .setAdvertise(false)
	        .setConfiguration(config)
	        .build();
       // @formatter:on
	appender.start();
	config.addAppender(appender);
	AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
	AppenderRef[] refs = new AppenderRef[] { ref };
	LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "testlog4j2refresh", "true", refs,
			null, config, null);
	loggerConfig.addAppender(appender, null, null);
	config.addLogger("testlog4j2refresh", loggerConfig);
	ctx.stop();
	ctx.start(config);

	log.error("Info message");
}
 
Example 12
Source File: Configurator.java    From logging-log4j2 with Apache License 2.0 3 votes vote down vote up
/**
 * Shuts down the given logger context.
 * <p>
 * Log4j can start threads to perform certain actions like file rollovers; calling this method with a positive
 * timeout will block until the rollover thread is done.
 * </p>
 *
 * @param ctx
 *            the logger context to shut down, may be null.
 * @param timeout
 *            the maximum time to wait
 * @param timeUnit
 *            the time unit of the timeout argument
 * @return {@code true} if the logger context terminated and {@code false} if the timeout elapsed before
 *         termination.
 *
 * @see LoggerContext#stop(long, TimeUnit)
 *
 * @since 2.7
 */
public static boolean shutdown(final LoggerContext ctx, final long timeout, final TimeUnit timeUnit) {
    if (ctx != null) {
        return ctx.stop(timeout, timeUnit);
    }
    return true;
}
 
Example 13
Source File: Configurator.java    From logging-log4j2 with Apache License 2.0 2 votes vote down vote up
/**
 * Shuts down the given logger context. This request does not wait for Log4j tasks to complete.
 * <p>
 * Log4j starts threads to perform certain actions like file rollovers; calling this method will not wait until the
 * rollover thread is done. When this method returns, these tasks' status are undefined, the tasks may be done or
 * not.
 * </p>
 * 
 * @param ctx
 *            the logger context to shut down, may be null.
 */
public static void shutdown(final LoggerContext ctx) {
    if (ctx != null) {
        ctx.stop();
    }
}