protected void loadConfiguration(String location, LogFile logFile) { Assert.notNull(location, "Location must not be null"); try { LoggerContext ctx = getLoggerContext(); URL url = ResourceUtils.getURL(location); ConfigurationSource source = getConfigurationSource(url); ctx.start(ConfigurationFactory.getInstance().getConfiguration(ctx, source)); } catch (Exception ex) { throw new IllegalStateException( "Could not initialize Log4J2 logging from " + location, ex); } }
@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(); }
@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()); } }
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); } }
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()); }
context.start(new CompositeConfiguration(configurations));
LoggerContext getLoggerContext(final ClassLoader classLoader) { LoggerContext ctx; try { final int key = computeKey(classLoader); // If possible, avoid using Guava cache since the callable puts unwanted pressure on the garbage collector. ctx = builtContexts.get(key); if (ctx == null) { synchronized (this) { ctx = builtContexts.get(key); if (ctx == null) { ctx = doGetLoggerContext(classLoader, key); } } } } catch (ExecutionException e) { throw new MuleRuntimeException(createStaticMessage("Could not init logger context "), e); } if (ctx.getState() == LifeCycle.State.INITIALIZED) { synchronized (this) { if (ctx.getState() == LifeCycle.State.INITIALIZED) { ctx.start(); } } } return ctx; }
@Override public void start(final Configuration config) { maybeStartHelper(config); super.start(config); }
@Override public void start() { loggerDisruptor.start(); super.start(); }
@Nonnull protected LoggerContext createLoggerContext(@Nonnull Log4J2BasedLoggingEnvironmentConfiguration requirement) { final org.apache.logging.log4j.core.LoggerContext result = new org.apache.logging.log4j.core.LoggerContext(FQCN); result.start(createConfigurationFor(requirement)); return result; }
private LoggerContext getCustomLoggerContext(Level log4jLevel) throws YggdrasilException { LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get(); if (ctx == null) { ctx = new CustomLoggerContext(); } if (ctx.getState() == LifeCycle.State.INITIALIZED) { ctx.start(new CustomLoggerConfiguration(log4jLevel)); } return ctx; }
public Logger getLogger() { if(!this.context.isStarted()) this.context.start(this.cfg); Collection<org.apache.logging.log4j.core.Logger> loggers = this.context.getLoggers(); List<String> lnames = this.context.getLoggers().stream() .map(l -> { String name = l.getName(); System.out.println(name); return name; }) .collect(Collectors.toList()); Logger log = this.context.getLogger(this.ctxName); return log; }
private void configureDefaults() { if (m_log4jContext == null) { m_log4jContext = new LoggerContext(LOGGER_CONTEXT_NAME); } m_log4jContext.start(new DefaultConfiguration()); String levelName; levelName = m_bundleContext.getProperty( DEFAULT_SERVICE_LOG_LEVEL ); if( levelName == null ) { levelName = "DEBUG"; } else { levelName = levelName.trim(); } m_logLevel = convertLevel( levelName ); }
@Override public LoggerContext getContext(String fqcn, ClassLoader loader, Object externalContext, boolean currentContext) { final LoggerContext ctx = customLoggerContext; if(externalContext != null && ctx.getExternalContext() == null) { ctx.setExternalContext(externalContext); } if(ctx.getState() == LifeCycle.State.INITIALIZED) { ctx.start(); } return ctx; }
@Override public void setConfigLocationUri(final String configLocation) throws URISyntaxException, IOException { if (configLocation == null || configLocation.isEmpty()) { throw new IllegalArgumentException("Missing configuration location"); } LOGGER.debug("---------"); LOGGER.debug("Remote request to reconfigure using location " + configLocation); final File configFile = new File(configLocation); ConfigurationSource configSource = null; if (configFile.exists()) { LOGGER.debug("Opening config file {}", configFile.getAbsolutePath()); configSource = new ConfigurationSource(new FileInputStream(configFile), configFile); } else { final URL configURL = new URL(configLocation); LOGGER.debug("Opening config URL {}", configURL); configSource = new ConfigurationSource(configURL.openStream(), configURL); } final Configuration config = ConfigurationFactory.getInstance().getConfiguration(loggerContext, configSource); loggerContext.start(config); LOGGER.debug("Completed remote request to reconfigure."); }
/** * 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; }
@Override public void setConfigText(final String configText, final String charsetName) { LOGGER.debug("---------"); LOGGER.debug("Remote request to reconfigure from config text."); try { final InputStream in = new ByteArrayInputStream(configText.getBytes(charsetName)); final ConfigurationSource source = new ConfigurationSource(in); final Configuration updated = ConfigurationFactory.getInstance().getConfiguration(loggerContext, source); loggerContext.start(updated); LOGGER.debug("Completed remote request to reconfigure from config text."); } catch (final Exception ex) { final String msg = "Could not reconfigure from config text"; LOGGER.error(msg, ex); throw new IllegalArgumentException(msg, ex); } }
@Override public LoggerContext getContext(String fqcn, ClassLoader loader, Object externalContext, boolean currentContext, URI configLocation, String name) { final LoggerContext ctx = customLoggerContext; 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) { THREAD_CONTEXT.set(ctx); final Configuration config = ConfigurationFactory.getInstance().getConfiguration(name, configLocation); StatusLogger.getLogger().debug("Starting LoggerContext[name={}] from configuration at {}", ctx.getName(), configLocation); ctx.start(config); THREAD_CONTEXT.remove(); } else { ctx.start(); } } return ctx; } }
/** * Initialize Log4J, including setting the web app root system property. */ public static void initLogging(MagnoliaConfigurationProperties configurationProperties, FileSystemHelper fileSystemHelper) { // can't use log4j yet log("Initializing Log4J"); //TODO: should provide a new default log4j2.xml? In case of migration and legacy system doesn't have new log4j.xml with new syntax, default fallback would help log4j2 start successfully. String log4jFileName = configurationProperties.getProperty(LOG4J_CONFIG); if (StringUtils.isNotEmpty(log4jFileName)) { final String config; try { config = fileSystemHelper.getTokenizedConfigFile(log4jFileName); } catch (IOException e) { log("Cannot load config file [" + log4jFileName + "], got a IOException :" + e.getMessage()); return; } try (InputStream log4jConfigStream = IOUtils.toInputStream(config)) { ConfigurationSource source = new ConfigurationSource(log4jConfigStream); Configuration configuration = ConfigurationFactory.getInstance().getConfiguration(null, source); ((LoggerContext) LogManager.getContext(false)).start(configuration); } catch (IOException ex) { log("Cannot load log configuration with config file [" + config + "], get IOException: " + ex.getMessage()); } } }
/** * 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; }