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

The following examples show how to use org.apache.logging.log4j.core.LoggerContext#start() . 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: Log4j2Test.java    From sofa-common-tools with Apache License 2.0 6 votes vote down vote up
@Test
public void testIndependentSpaceLog4j2() throws URISyntaxException {
    //  LoggerFactory.getLogger(LogbackTest.class).info("xxx");
    URL url1 = LogbackTest.class.getResource("/com/alipay/sofa/rpc/log/log4j2/log-conf.xml");
    LoggerContext lc1 = new LoggerContext("rest", null, url1.toURI());
    lc1.start();
    org.apache.logging.log4j.core.Logger logger1 = lc1.getLogger("com.foo.Bar");
    logger1.info("log4j2 - 1");
    Assert.assertNotNull(logger1);

    //log4j2 logger2
    URL url2 = LogbackTest.class.getResource("/com/alipay/sofa/rpc/log/log4j2/log4j2_b.xml");
    LoggerContext lc2 = new LoggerContext("rpc", null, url2.toURI());
    lc2.start();
    org.apache.logging.log4j.core.Logger logger2 = lc2.getLogger("com.foo.Bar2");
    logger2.info("log4j2 - 2");
    Assert.assertNotNull(logger2);
    Assert.assertNotSame(logger1, logger2);
}
 
Example 2
Source File: LoggerUtil.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * <p>
 * This method loads the required properties into log4j for the logger
 * </p>
 * 
 * @param logFileDir
 *            Log file directory
 * @param taskAttemptID
 *            The task attempt id
 * 
 * @throws IOException
 *             If any error occurs
 * @throws URISyntaxException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws TransformerException
 */
public static void loadLogger(String logFileDir, String taskAttemptID) throws IOException, URISyntaxException, ParserConfigurationException,
		SAXException, TransformerException {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    ctx.reconfigure();
       Configuration config = ctx.getConfiguration();
       MemoryMappedFileAppender memoryMappedfileAppender = createMemoryMappedFileAppender(config, LOG_APPENDER_NAME + taskAttemptID, logFileDir, taskAttemptID, 0);
       memoryMappedfileAppender.start();
    AppenderRef[] ar = new AppenderRef [1];
       ar[0] = AppenderRef.createAppenderRef(LOG_APPENDER_NAME + taskAttemptID , Level.INFO, null);
       LoggerConfig lgf = LoggerConfig.createLogger("false",Level.INFO , LOG_CATEGORY + taskAttemptID , null, ar, null, config, null);
       config.addLogger(LOG_CATEGORY + taskAttemptID, lgf);
       ctx.getLogger(LOG_CATEGORY + taskAttemptID).addAppender(memoryMappedfileAppender);
       ctx.updateLoggers();
       ctx.start();
	mapReduceLoggers = new ArrayList<Logger>(1);
	mapReduceLoggers.add(LogManager.getLogger(LOG_CATEGORY + taskAttemptID));
	LOG.debug("Finished loading logger");

}
 
Example 3
Source File: Log4jContextFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Loads the LoggerContext using the ContextSelector.
 * @param fqcn The fully qualified class name of the caller.
 * @param loader The ClassLoader to use or null.
 * @param externalContext An external context (such as a ServletContext) to be associated with the LoggerContext.
 * @param currentContext If true returns the current Context, if false returns the Context appropriate
 * for the caller if a more appropriate Context can be determined.
 * @param source The configuration source.
 * @return The LoggerContext.
 */
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext,
                                final boolean currentContext, final ConfigurationSource source) {
    final LoggerContext ctx = selector.getContext(fqcn, loader, currentContext, null);
    if (externalContext != null && ctx.getExternalContext() == null) {
        ctx.setExternalContext(externalContext);
    }
    if (ctx.getState() == LifeCycle.State.INITIALIZED) {
        if (source != null) {
            ContextAnchor.THREAD_CONTEXT.set(ctx);
            final Configuration config = ConfigurationFactory.getInstance().getConfiguration(ctx, source);
            LOGGER.debug("Starting LoggerContext[name={}] from configuration {}", ctx.getName(), source);
            ctx.start(config);
            ContextAnchor.THREAD_CONTEXT.remove();
        } else {
            ctx.start();
        }
    }
    return ctx;
}
 
Example 4
Source File: Log4jContextFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Loads the LoggerContext using the ContextSelector using the provided Configuration
 * @param fqcn The fully qualified class name of the caller.
 * @param loader The ClassLoader to use or null.
 * @param externalContext An external context (such as a ServletContext) to be associated with the LoggerContext.
 * @param currentContext If true returns the current Context, if false returns the Context appropriate
 * for the caller if a more appropriate Context can be determined.
 * @param configuration The Configuration.
 * @return The LoggerContext.
 */
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext,
        final boolean currentContext, final Configuration configuration) {
    final LoggerContext ctx = selector.getContext(fqcn, loader, currentContext, null);
    if (externalContext != null && ctx.getExternalContext() == null) {
        ctx.setExternalContext(externalContext);
    }
    if (ctx.getState() == LifeCycle.State.INITIALIZED) {
        ContextAnchor.THREAD_CONTEXT.set(ctx);
        try {
            ctx.start(configuration);
        } finally {
            ContextAnchor.THREAD_CONTEXT.remove();
        }
    }
    return ctx;
}
 
Example 5
Source File: Log4jContextFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Loads the LoggerContext using the ContextSelector.
 * @param fqcn The fully qualified class name of the caller.
 * @param loader The ClassLoader to use or null.
 * @param externalContext An external context (such as a ServletContext) to be associated with the LoggerContext.
 * @param currentContext If true returns the current Context, if false returns the Context appropriate
 * for the caller if a more appropriate Context can be determined.
 * @param configLocation The location of the configuration for the LoggerContext (or null).
 * @return The LoggerContext.
 */
@Override
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext,
                                final boolean currentContext, final URI configLocation, final String name) {
    final LoggerContext ctx = selector.getContext(fqcn, loader, currentContext, configLocation);
    if (externalContext != null && ctx.getExternalContext() == null) {
        ctx.setExternalContext(externalContext);
    }
    if (name != null) {
    	ctx.setName(name);
    }
    if (ctx.getState() == LifeCycle.State.INITIALIZED) {
        if (configLocation != null || name != null) {
            ContextAnchor.THREAD_CONTEXT.set(ctx);
            final Configuration config = ConfigurationFactory.getInstance().getConfiguration(ctx, name, configLocation);
            LOGGER.debug("Starting LoggerContext[name={}] from configuration at {}", ctx.getName(), configLocation);
            ctx.start(config);
            ContextAnchor.THREAD_CONTEXT.remove();
        } else {
            ctx.start();
        }
    }
    return ctx;
}
 
Example 6
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 7
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 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: 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 10
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 11
Source File: JiraLog4j2_2134Test.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRefreshMinimalCodeStart() {
	Logger log = LogManager.getLogger(this.getClass());
	final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
	final Configuration config = ctx.getConfiguration();
	ctx.start(config);

	log.error("Info message");
}
 
Example 12
Source File: Log4jContextFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext,
        final boolean currentContext, final List<URI> configLocations, final String name) {
    final LoggerContext ctx = selector
            .getContext(fqcn, loader, currentContext, null/*this probably needs to change*/);
    if (externalContext != null && ctx.getExternalContext() == null) {
        ctx.setExternalContext(externalContext);
    }
    if (name != null) {
        ctx.setName(name);
    }
    if (ctx.getState() == LifeCycle.State.INITIALIZED) {
        if ((configLocations != null && !configLocations.isEmpty())) {
            ContextAnchor.THREAD_CONTEXT.set(ctx);
            final List<AbstractConfiguration> configurations = new ArrayList<>(configLocations.size());
            for (final URI configLocation : configLocations) {
                final Configuration currentReadConfiguration = ConfigurationFactory.getInstance()
                        .getConfiguration(ctx, name, configLocation);
                if (currentReadConfiguration instanceof AbstractConfiguration) {
                    configurations.add((AbstractConfiguration) currentReadConfiguration);
                } else {
                    LOGGER.error(
                            "Found configuration {}, which is not an AbstractConfiguration and can't be handled by CompositeConfiguration",
                            configLocation);
                }
            }
            final CompositeConfiguration compositeConfiguration = new CompositeConfiguration(configurations);
            LOGGER.debug("Starting LoggerContext[name={}] from configurations at {}", ctx.getName(),
                    configLocations);
            ctx.start(compositeConfiguration);
            ContextAnchor.THREAD_CONTEXT.remove();
        } else {
            ctx.start();
        }
    }
    return ctx;
}
 
Example 13
Source File: Log4jContextFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Loads the LoggerContext using the ContextSelector.
 * @param fqcn The fully qualified class name of the caller.
 * @param loader The ClassLoader to use or null.
 * @param currentContext If true returns the current Context, if false returns the Context appropriate
 * for the caller if a more appropriate Context can be determined.
 * @param externalContext An external context (such as a ServletContext) to be associated with the LoggerContext.
 * @return The LoggerContext.
 */
@Override
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext,
                                final boolean currentContext) {
    final LoggerContext ctx = selector.getContext(fqcn, loader, currentContext);
    if (externalContext != null && ctx.getExternalContext() == null) {
        ctx.setExternalContext(externalContext);
    }
    if (ctx.getState() == LifeCycle.State.INITIALIZED) {
        ctx.start();
    }
    return ctx;
}
 
Example 14
Source File: Log4jWebInitializerImpl.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void initializeJndi(final String location) {
    final URI configLocation = getConfigURI(location);

    if (this.name == null) {
        throw new IllegalStateException("A log4jContextName context parameter is required");
    }

    LoggerContext context;
    final LoggerContextFactory factory = LogManager.getFactory();
    if (factory instanceof Log4jContextFactory) {
        final ContextSelector selector = ((Log4jContextFactory) factory).getSelector();
        if (selector instanceof NamedContextSelector) {
            this.namedContextSelector = (NamedContextSelector) selector;
            context = this.namedContextSelector.locateContext(this.name, this.servletContext, configLocation);
            ContextAnchor.THREAD_CONTEXT.set(context);
            if (context.isInitialized()) {
                context.start();
            }
            ContextAnchor.THREAD_CONTEXT.remove();
        } else {
            LOGGER.warn("Potential problem: Selector is not an instance of NamedContextSelector.");
            return;
        }
    } else {
        LOGGER.warn("Potential problem: LoggerContextFactory is not an instance of Log4jContextFactory.");
        return;
    }
    this.loggerContext = context;
    LOGGER.debug("Created logger context for [{}] using [{}].", this.name, context.getClass().getClassLoader());
}
 
Example 15
Source File: Log4j2Logger.java    From Zebra with Apache License 2.0 5 votes vote down vote up
private static synchronized void init() {
	URL url = Log4j2Logger.class.getClassLoader().getResource("zebra_log4j2.xml");

	try {
		if (null == url) {
			throw new ZebraException("log4j2 resource load failed");
		}

		LoggerContext ctx = new LoggerContext("Zebra", null, url.toURI());
		ctx.start();
		context = ctx;
	} catch (Exception e) {
		throw new ZebraException("Fail to initialize log4j2", e);
	}
}
 
Example 16
Source File: LogConfigurator.java    From crate with Apache License 2.0 4 votes vote down vote up
private static void configure(final Settings settings, final Path configsPath, final Path logsPath) throws IOException, UserException {
    Objects.requireNonNull(settings);
    Objects.requireNonNull(configsPath);
    Objects.requireNonNull(logsPath);

    loadLog4jPlugins();

    setLogConfigurationSystemProperty(logsPath, settings);
    // we initialize the status logger immediately otherwise Log4j will complain when we try to get the context
    configureStatusLogger();

    final LoggerContext context = (LoggerContext) LogManager.getContext(false);

    final Set<String> locationsWithDeprecatedPatterns = Collections.synchronizedSet(new HashSet<>());
    final List<AbstractConfiguration> configurations = new ArrayList<>();
    /*
     * Subclass the properties configurator to hack the new pattern in
     * place so users don't have to change log4j2.properties in
     * a minor release. In 7.0 we'll remove this and force users to
     * change log4j2.properties. If they don't customize log4j2.properties
     * then they won't have to do anything anyway.
     *
     * Everything in this subclass that isn't marked as a hack is copied
     * from log4j2's source.
     */
    final PropertiesConfigurationFactory factory = new PropertiesConfigurationFactory() {
        @Override
        public PropertiesConfiguration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
            final Properties properties = new Properties();
            try (InputStream configStream = source.getInputStream()) {
                properties.load(configStream);
            } catch (final IOException ioe) {
                throw new ConfigurationException("Unable to load " + source.toString(), ioe);
            }
            // Hack the new pattern into place
            for (String name : properties.stringPropertyNames()) {
                if (false == name.endsWith(".pattern")) continue;
                // Null is weird here but we can't do anything with it so ignore it
                String value = properties.getProperty(name);
                if (value == null) continue;
                // Tests don't need to be changed
                if (value.contains("%test_thread_info")) continue;
                /*
                 * Patterns without a marker are sufficiently customized
                 * that we don't have an opinion about them.
                 */
                if (false == value.contains("%marker")) continue;
                if (false == value.contains("%node_name")) {
                    locationsWithDeprecatedPatterns.add(source.getLocation());
                    properties.setProperty(name, value.replace("%marker", "[%node_name]%marker "));
                }
            }
            // end hack
            return new PropertiesConfigurationBuilder()
                    .setConfigurationSource(source)
                    .setRootProperties(properties)
                    .setLoggerContext(loggerContext)
                    .build();
        }
    };
    final Set<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
    Files.walkFileTree(configsPath, options, Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            if (file.getFileName().toString().equals("log4j2.properties")) {
                configurations.add((PropertiesConfiguration) factory.getConfiguration(context, file.toString(), file.toUri()));
            }
            return FileVisitResult.CONTINUE;
        }
    });

    if (configurations.isEmpty()) {
        throw new UserException(
                ExitCodes.CONFIG,
                "no log4j2.properties found; tried [" + configsPath + "] and its subdirectories");
    }

    context.start(new CompositeConfiguration(configurations));

    configureLoggerLevels(settings);

    final String deprecatedLocationsString = String.join("\n  ", locationsWithDeprecatedPatterns);
    if (deprecatedLocationsString.length() > 0) {
        LogManager.getLogger(LogConfigurator.class).warn("Some logging configurations have %marker but don't have %node_name. "
                + "We will automatically add %node_name to the pattern to ease the migration for users who customize "
                + "log4j2.properties but will stop this behavior in 7.0. You should manually replace `%node_name` with "
                + "`[%node_name]%marker ` in these locations:\n  {}", deprecatedLocationsString);
    }
}
 
Example 17
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 18
Source File: BHBot.java    From BHBot with GNU General Public License v3.0 4 votes vote down vote up
private void reloadLogger() {
    ConfigurationFactory configFactory = new BHBotConfigurationFactory();
    ConfigurationFactory.setConfigurationFactory(configFactory);
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    ctx.start(configFactory.getConfiguration(ctx, ConfigurationSource.NULL_SOURCE));
}