下面列出了怎么用org.apache.logging.log4j.core.impl.Log4jContextFactory的API类实例代码及写法,或者点击链接到github查看源代码。
@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) {
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;
}
/**
* Reconfigure using an already constructed Configuration.
* @param configuration The configuration.
* @since 2.13.0
*/
public static void reconfigure(final Configuration configuration) {
try {
final Log4jContextFactory factory = getFactory();
if (factory != null) {
factory.getContext(FQCN, null, null, false)
.reconfigure(configuration);
}
} catch (final Exception ex) {
LOGGER.error("There was a problem initializing the LoggerContext using configuration {}",
configuration.getName(), ex);
}
}
/**
* Reload the existing reconfiguration.
* @since 2.12.0
*/
public static void reconfigure() {
try {
Log4jContextFactory factory = getFactory();
if (factory != null) {
factory.getSelector().getContext(FQCN, null, false).reconfigure();
} else {
LOGGER.warn("Unable to reconfigure - Log4j has not been initialized.");
}
} catch (final Exception ex) {
LOGGER.error("Error encountered trying to reconfigure logging", ex);
}
}
/**
* Reconfigure with a potentially new configuration.
* @param uri The location of the configuration.
* @since 2.12.0
*/
public static void reconfigure(final URI uri) {
try {
Log4jContextFactory factory = getFactory();
if (factory != null) {
factory.getSelector().getContext(FQCN, null, false).setConfigLocation(uri);
} else {
LOGGER.warn("Unable to reconfigure - Log4j has not been initialized.");
}
} catch (final Exception ex) {
LOGGER.error("Error encountered trying to reconfigure logging", ex);
}
}
@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());
}