下面列出了org.springframework.boot.logging.LogFile#org.apache.logging.log4j.core.config.ConfigurationFactory 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Setup
public void setup() throws Exception {
connectionHSQLDB = getConnectionHSQLDB();
connectionH2 = getConnectionH2();
createTable(connectionHSQLDB, toCreateTableSqlStringHQLDB("fmLogEntry"));
createTable(connectionH2, toCreateTableSqlStringH2("fmLogEntry"));
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "log4j2-jdbc-appender.xml");
final LoggerContext context = LoggerContext.getContext(false);
if (context.getConfiguration() instanceof DefaultConfiguration) {
context.reconfigure();
}
StatusLogger.getLogger().reset();
loggerH2 = LogManager.getLogger("H2Logger");
loggerHSQLDB = LogManager.getLogger("HSQLDBLogger");
}
@Before
public void setUp() throws Exception {
final File file = new File("target/file-channel");
deleteFiles(file);
/*
* Clear out all other appenders associated with this logger to ensure we're
* only hitting the Avro appender.
*/
final int primaryPort = AvailablePortFinder.getNextAvailable();
final int altPort = AvailablePortFinder.getNextAvailable();
System.setProperty("primaryPort", Integer.toString(primaryPort));
System.setProperty("alternatePort", Integer.toString(altPort));
primary = new EventCollector(primaryPort);
alternate = new EventCollector(altPort);
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG);
ctx = LoggerContext.getContext(false);
ctx.reconfigure();
}
@After
public void teardown() throws Exception {
System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
ctx.reconfigure();
primary.stop();
alternate.stop();
final File file = new File("target/file-channel");
deleteFiles(file);
final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
final Set<ObjectName> names = server.queryNames(new ObjectName("org.apache.flume.*:*"), null);
for (final ObjectName name : names) {
try {
server.unregisterMBean(name);
} catch (final Exception ex) {
System.out.println("Unable to unregister " + name.toString());
}
}
}
@Before
public void setUp() throws Exception {
final File file = new File("target/persistent");
deleteFiles(file);
/*
* Clear out all other appenders associated with this logger to ensure we're
* only hitting the Avro appender.
*/
final int primaryPort = AvailablePortFinder.getNextAvailable();
final int altPort = AvailablePortFinder.getNextAvailable();
System.setProperty("primaryPort", Integer.toString(primaryPort));
System.setProperty("alternatePort", Integer.toString(altPort));
primary = new EventCollector(primaryPort);
alternate = new EventCollector(altPort);
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG);
ctx = LoggerContext.getContext(false);
ctx.reconfigure();
}
@After
public void teardown() throws Exception {
System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
ctx.reconfigure();
primary.stop();
alternate.stop();
final File file = new File("target/file-channel");
deleteFiles(file);
final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
final Set<ObjectName> names = server.queryNames(new ObjectName("org.apache.flume.*:*"), null);
for (final ObjectName name : names) {
try {
server.unregisterMBean(name);
} catch (final Exception ex) {
System.out.println("Unable to unregister " + name.toString());
}
}
}
@After
public void teardown() throws Exception {
System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
ctx.reconfigure();
primary.stop();
alternate.stop();
final File file = new File("target/file-channel");
deleteFiles(file);
final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
final Set<ObjectName> names = server.queryNames(new ObjectName("org.apache.flume.*:*"), null);
for (final ObjectName name : names) {
try {
server.unregisterMBean(name);
} catch (final Exception ex) {
System.out.println("Unable to unregister " + name.toString());
}
}
}
@Before
public void setUp() throws Exception {
final File file = new File("target/persistent");
deleteFiles(file);
/*
* Clear out all other appenders associated with this logger to ensure we're
* only hitting the Avro appender.
*/
final int primaryPort = AvailablePortFinder.getNextAvailable();
final int altPort = AvailablePortFinder.getNextAvailable();
System.setProperty("primaryPort", Integer.toString(primaryPort));
System.setProperty("alternatePort", Integer.toString(altPort));
primary = new EventCollector(primaryPort);
alternate = new EventCollector(altPort);
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG);
ctx = LoggerContext.getContext(false);
ctx.reconfigure();
}
public void tearDown() throws SQLException {
final LoggerContext context = LoggerContext.getContext(false);
try {
String appenderName = "databaseAppender";
final Appender appender = context.getConfiguration().getAppender(appenderName);
assertNotNull("The appender '" + appenderName + "' should not be null.", appender);
assertTrue("The appender should be a JpaAppender.", appender instanceof JpaAppender);
((JpaAppender) appender).getManager().close();
} finally {
System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
PropertiesUtil.getProperties().reload();
context.reconfigure();
StatusLogger.getLogger().reset();
try (Statement statement = this.connection.createStatement();) {
statement.execute("SHUTDOWN");
}
this.connection.close();
}
}
@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);
}
}
/**
* 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;
}
/**
* 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;
}
/**
* Reconfigures the context.
*/
private void reconfigure(final URI configURI) {
Object externalContext = externalMap.get(EXTERNAL_CONTEXT_KEY);
final ClassLoader cl = ClassLoader.class.isInstance(externalContext) ? (ClassLoader) externalContext : null;
LOGGER.debug("Reconfiguration started for context[name={}] at URI {} ({}) with optional ClassLoader: {}",
contextName, configURI, this, cl);
final Configuration instance = ConfigurationFactory.getInstance().getConfiguration(this, contextName, configURI, cl);
if (instance == null) {
LOGGER.error("Reconfiguration failed: No configuration found for '{}' at '{}' in '{}'", contextName, configURI, cl);
} else {
setConfiguration(instance);
/*
* instance.start(); Configuration old = setConfiguration(instance); updateLoggers(); if (old != null) {
* old.stop(); }
*/
final String location = configuration == null ? "?" : String.valueOf(configuration.getConfigurationSource());
LOGGER.debug("Reconfiguration complete for context[name={}] at URI {} ({}) with optional ClassLoader: {}",
contextName, location, this, cl);
}
}
@BeforeClass
public static void beforeClass() {
System.setProperty("AsyncLogger.ThreadNameStrategy", "UNCACHED");
System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
AsyncLoggerContextSelector.class.getName());
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
"AsyncLoggerTest.xml");
}
@Test
public void testCustomConfigurationFactory() {
try {
System.setProperty(ConfigurationFactory.CONFIGURATION_FACTORY_PROPERTY,
"org.apache.pulsar.log4j2.appender.builder.CustomConfigurationFactory");
System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
"org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
final Configuration config = ((LoggerContext) LogManager.getContext(false)).getConfiguration();
validate(config);
} finally {
System.getProperties().remove(Constants.LOG4J_CONTEXT_SELECTOR);
System.getProperties().remove(ConfigurationFactory.CONFIGURATION_FACTORY_PROPERTY);
}
}
@Override
void configureLogger() {
if (System.getProperty(ConfigurationFactory.CONFIGURATION_FACTORY_PROPERTY) != null) return;
System.setProperty(ConfigurationFactory.CONFIGURATION_FACTORY_PROPERTY, ESLoggerConfigFactory.class.getName());
// refer to org.apache.logging.log4j.core.jmx.Server.PROPERTY_DISABLE_JMX, disable to reduce overhead
System.setProperty("log4j2.disable.jmx", "true");
ESLoggerConfigFactory.configureLogger();
}
@AfterClass
public static void tearDown() throws Exception {
Field factories = ConfigurationFactory.class.getDeclaredField("factories");
factories.setAccessible(true);
factories.set(null, null);
ConfigurationFactory.resetConfigurationFactory();
}
@AfterClass
public static void cleanupClass() {
System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
System.clearProperty(LOGBACK_CONF);
System.clearProperty(LOG4J_CONF);
new File("target/testlog4j.log").deleteOnExit();
new File("target/testlog4j2.log").deleteOnExit();
new File("target/testlogback.log").deleteOnExit();
}
@BeforeClass
public static void beforeClass() {
System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
AsyncLoggerContextSelector.class.getName());
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
"NanoTimeToFileTest.xml");
}
@BeforeClass
public static void beforeClass() {
final File file = new File("target", "AsyncLoggerLocationTest.log");
file.delete();
System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
AsyncLoggerContextSelector.class.getName());
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
"AsyncLoggerLocationTest.xml");
}
@Override
protected String[] getSupportedTypes() {
if (!PropertiesUtil.getProperties().getBooleanProperty(ConfigurationFactory.LOG4J1_EXPERIMENTAL, Boolean.FALSE)) {
return null;
}
return new String[] {".properties"};
}
@BeforeClass
public static void setUpClass() {
rbUS = ResourceBundle.getBundle("L7D", new Locale("en", "US"));
assertNotNull(rbUS);
rbFR = ResourceBundle.getBundle("L7D", new Locale("fr", "FR"));
assertNotNull("Got a null resource bundle.", rbFR);
rbCH = ResourceBundle.getBundle("L7D", new Locale("fr", "CH"));
assertNotNull("Got a null resource bundle.", rbCH);
ConfigurationFactory.setConfigurationFactory(configurationFactory);
}
@BeforeClass
public static void setupClass() {
StatusLogger.getLogger().setLevel(Level.OFF);
ConfigurationFactory.setConfigurationFactory(cf);
final LoggerContext ctx = LoggerContext.getContext();
ctx.reconfigure();
}
@BeforeClass
public static void beforeClass() {
System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
AsyncLoggerContextSelector.class.getName());
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
"AsyncLoggerTest.xml");
}
@AfterClass
public static void afterClass() {
System.clearProperty("AsyncLogger.RingBufferSize");
System.clearProperty("AsyncLoggerConfig.RingBufferSize");
System.clearProperty(Constants.LOG4J_CONTEXT_SELECTOR);
System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
System.clearProperty("log4j2.garbagefree.threadContextMap");
System.clearProperty("log4j2.is.webapp");
System.clearProperty("log4j2.threadContextMap");
}
@Test
public void testConsecutiveReconfigure() throws Exception {
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
"AsyncLoggerConfigTest2.xml");
final File file = new File("target", "AsyncLoggerConfigTest2.log");
assertTrue("Deleted old file before test", !file.exists() || file.delete());
final Logger log = LogManager.getLogger("com.foo.Bar");
final String msg = "Message before reconfig";
log.info(msg);
final LoggerContext ctx = LoggerContext.getContext(false);
ctx.reconfigure();
ctx.reconfigure();
final String msg2 = "Message after reconfig";
log.info(msg2);
CoreLoggerContexts.stopLoggerContext(file); // stop async thread
final BufferedReader reader = new BufferedReader(new FileReader(file));
final String line1 = reader.readLine();
final String line2 = reader.readLine();
reader.close();
file.delete();
assertNotNull("line1", line1);
assertNotNull("line2", line2);
assertTrue("line1 " + line1, line1.contains(msg));
assertTrue("line2 " + line2, line2.contains(msg2));
}
public void setUp(final String configFileName) throws SQLException {
this.connection = this.setUpConnection();
final String resource = "org/apache/logging/log4j/jpa/appender/" + configFileName;
assertNotNull(getClass().getClassLoader().getResource(resource));
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
resource);
PropertiesUtil.getProperties().reload();
final LoggerContext context = LoggerContext.getContext(false);
if (context.getConfiguration() instanceof DefaultConfiguration) {
context.reconfigure();
}
StatusLogger.getLogger().reset();
}
@BeforeClass
public static void beforeClass() {
System.setProperty("log4j2.is.webapp", "false");
System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getCanonicalName());
// Reuse the configuration from AsyncLoggerConfigTest4
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerConfigTest4.xml");
}
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;
}
public static HttpURLConnection createConnection(URL url, long lastModifiedMillis, SslConfiguration sslConfiguration)
throws IOException {
final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
AuthorizationProvider provider = ConfigurationFactory.getAuthorizationProvider();
if (provider != null) {
provider.addAuthorization(urlConnection);
}
urlConnection.setAllowUserInteraction(false);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("GET");
if (connectTimeoutMillis > 0) {
urlConnection.setConnectTimeout(connectTimeoutMillis);
}
if (readTimeoutMillis > 0) {
urlConnection.setReadTimeout(readTimeoutMillis);
}
String[] fileParts = url.getFile().split("\\.");
String type = fileParts[fileParts.length - 1].trim();
String contentType = isXml(type) ? XML : isJson(type) ? JSON : isProperties(type) ? PROPERTIES : TEXT;
urlConnection.setRequestProperty("Content-Type", contentType);
if (lastModifiedMillis > 0) {
urlConnection.setIfModifiedSince(lastModifiedMillis);
}
if (url.getProtocol().equals(HTTPS) && sslConfiguration != null) {
((HttpsURLConnection) urlConnection).setSSLSocketFactory(sslConfiguration.getSslSocketFactory());
if (!sslConfiguration.isVerifyHostName()) {
((HttpsURLConnection) urlConnection).setHostnameVerifier(LaxHostnameVerifier.INSTANCE);
}
}
return urlConnection;
}
@BeforeClass
public static void beforeClass() {
System.setProperty("log4j2.enable.threadlocals", "true");
System.setProperty("log4j2.enable.direct.encoders", "true");
System.setProperty("log4j2.is.webapp", "false");
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "EventParameterMemoryLeakTest.xml");
}