/** * We cannot presume that the default file name/location setting won't be changed by the user. * Therefore, we should be able to retrieve that info from the underlying logging mechanism * by iterating over appenders. */ private List<Path> getActiveLogFilePaths() { LoggerContextFactory factory = LogManager.getFactory(); ContextSelector selector = ((Log4jContextFactory) factory).getSelector(); List<Path> fileNameList = new ArrayList<>(); for (LoggerContext ctx : selector.getLoggerContexts()) { for (Appender appender : ctx.getConfiguration().getAppenders().values()) { String fileName = extractFileName(appender); if (fileName != null) { fileNameList.add(Paths.get(fileName)); } } } return fileNameList; }
@Before public void setup() throws Exception { // Create mock objects mockLog4jContextFactory = mock(Log4jContextFactory.class); whenNew(Log4jContextFactory.class).withNoArguments().thenReturn(mockLog4jContextFactory); mockLoggerContext = mock(LoggerContext.class); mockLogger = mock(Logger.class); when(mockLog4jContextFactory.getContext(anyString(), any(ClassLoader.class), any(), anyBoolean(), any(URI.class), anyString())).thenReturn(mockLoggerContext); when(mockLoggerContext.getRootLogger()).thenReturn(mockLogger); mockRequest = mock(Request.class); mockResponse = mock(Response.class); mockAccessLog = mock(AccessLog.class); whenNew(AccessLog.class).withArguments(mockRequest, mockResponse).thenReturn(mockAccessLog); // Create actual objects enabledSupplier = () -> true; disabledSupplier = () -> false; failedAccessLog = new TestLog4JAccessLog(NON_EXISTING_FILE_PATH, enabledSupplier); String filePath = getClass().getClassLoader().getResource(ACCESS_CONFIG_FILE_PATH).getPath(); enabledAccessLog = new TestLog4JAccessLog(filePath, enabledSupplier); disabledAccessLog = new TestLog4JAccessLog(filePath, disabledSupplier); }
/** * Initializes the Logging Context. * @param loader The ClassLoader for the Context (or null). * @param source The InputSource for the configuration. * @param externalContext The external context to be attached to the LoggerContext. * @return The LoggerContext. */ public static LoggerContext initialize(final ClassLoader loader, final ConfigurationSource source, final Object externalContext) { try { final Log4jContextFactory factory = getFactory(); return factory == null ? null : factory.getContext(FQCN, loader, externalContext, false, source); } catch (final Exception ex) { LOGGER.error("There was a problem obtaining a LoggerContext using the configuration source [{}]", source, ex); } return null; }
public static List<? extends LoggerContext> getContexts() { LoggerContextFactory factory = org.apache.logging.log4j.LogManager.getFactory(); if(factory instanceof SimpleLoggerContextFactory) { return Collections.singletonList(factory.getContext(null, null, null, true)); } return ((Log4jContextFactory) org.apache.logging.log4j.LogManager.getFactory()).getSelector().getLoggerContexts(); }
@Override protected void doStart() throws Exception { File accessConfigFile = new File(accessConfigFilePath); if (!accessConfigFile.isFile()) { throw new Exception("Log4J access config file not found: " + accessConfigFilePath); } loggerContext = new Log4jContextFactory().getContext(Log4JAccessLog.class.getName(), null, null, true, accessConfigFile.toURI(), "PoseidonLog4JAccess"); logger = loggerContext.getRootLogger(); }
private void initializeJndi(final String location) throws UnavailableException { URI configLocation = null; if (location != null) { try { configLocation = new URI(location); } catch (final Exception e) { this.servletContext.log("Unable to convert configuration location [" + location + "] to a URI!", e); } } if (this.name == null) { throw new UnavailableException("A log4jContextName context parameter is required"); } LoggerContext loggerContext; final LoggerContextFactory factory = LogManager.getFactory(); if (factory instanceof Log4jContextFactory) { final ContextSelector selector = ((Log4jContextFactory) factory).getSelector(); if (selector instanceof NamedContextSelector) { this.selector = (NamedContextSelector) selector; loggerContext = this.selector.locateContext(this.name, this.servletContext, configLocation); ContextAnchor.THREAD_CONTEXT.set(loggerContext); if (loggerContext.getStatus() == LoggerContext.Status.INITIALIZED) { loggerContext.start(); } ContextAnchor.THREAD_CONTEXT.remove(); } else { this.servletContext.log("Potential problem: Selector is not an instance of NamedContextSelector."); return; } } else { this.servletContext.log("Potential problem: Factory is not an instance of Log4jContextFactory."); return; } this.loggerContext = loggerContext; this.servletContext.log("Created logger context for [" + this.name + "] using [" + loggerContext.getClass().getClassLoader() + "]."); }
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()); }
/** * Returns the {@code ContextSelector} of the current {@code Log4jContextFactory}. * * @return the {@code ContextSelector} of the current {@code Log4jContextFactory} */ private static ContextSelector getContextSelector() { final LoggerContextFactory factory = LogManager.getFactory(); if (factory instanceof Log4jContextFactory) { final ContextSelector selector = ((Log4jContextFactory) factory).getSelector(); return selector; } return null; }
private static Log4jContextFactory getFactory() { final LoggerContextFactory factory = LogManager.getFactory(); if (factory instanceof Log4jContextFactory) { return (Log4jContextFactory) factory; } else if (factory != null) { LOGGER.error("LogManager returned an instance of {} which does not implement {}. Unable to initialize Log4j.", factory.getClass().getName(), Log4jContextFactory.class.getName()); return null; } else { LOGGER.fatal("LogManager did not return a LoggerContextFactory. This indicates something has gone terribly wrong!"); return null; } }
/** * Initializes the Logging Context. * @param name The Context name. * @param loader The ClassLoader for the Context (or null). * @param configLocation The configuration for the logging context (or null). * @param externalContext The external context to be attached to the LoggerContext * @return The LoggerContext. */ public static LoggerContext initialize(final String name, final ClassLoader loader, final URI configLocation, final Object externalContext) { try { final Log4jContextFactory factory = getFactory(); return factory == null ? null : factory.getContext(FQCN, loader, externalContext, false, configLocation, name); } catch (final Exception ex) { LOGGER.error("There was a problem initializing the LoggerContext [{}] using configuration at [{}].", name, configLocation, ex); } return null; }
public static LoggerContext initialize(final String name, final ClassLoader loader, final List<URI> configLocations, final Object externalContext) { try { final Log4jContextFactory factory = getFactory(); return factory == null ? null : factory.getContext(FQCN, loader, externalContext, false, configLocations, name); } catch (final Exception ex) { LOGGER.error("There was a problem initializing the LoggerContext [{}] using configurations at [{}].", name, configLocations, ex); } return null; }
/** * Initializes the Logging Context. * @param loader The ClassLoader. * @param configuration The Configuration. * @param externalContext - The external context to be attached to the LoggerContext. * @return The LoggerContext. */ public static LoggerContext initialize(final ClassLoader loader, final Configuration configuration, final Object externalContext) { try { final Log4jContextFactory factory = getFactory(); return factory == null ? null : factory.getContext(FQCN, loader, externalContext, false, configuration); } catch (final Exception ex) { LOGGER.error("There was a problem initializing the LoggerContext using configuration {}", configuration.getName(), ex); } return null; }
@Test public void testShutdownCallbackRegistry() throws Exception { final LoggerContext context = ctx.getLoggerContext(); assertTrue("LoggerContext should be started", context.isStarted()); assertThat(Registry.CALLBACKS, hasSize(1)); Registry.shutdown(); assertTrue("LoggerContext should be stopped", context.isStopped()); assertThat(Registry.CALLBACKS, hasSize(0)); final ContextSelector selector = ((Log4jContextFactory) LogManager.getFactory()).getSelector(); assertThat(selector.getLoggerContexts(), not(hasItem(context))); }
@Test public void testShutdownHookDisabled() { assertFalse( "Shutdown hook should be disabled by default in web applications", ((Log4jContextFactory) LogManager.getFactory()).isShutdownHookEnabled()); }