You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@logging.apache.org by vy...@apache.org on 2024/01/17 15:01:36 UTC
(logging-log4j2) 01/01: Remove ineffective tests
This is an automated email from the ASF dual-hosted git repository.
vy pushed a commit to branch main-remove-ineffective-tests
in repository https://gitbox.apache.org/repos/asf/logging-log4j2.git
commit d7c6184962177e3db39f90d4d79cbf4462c1718d
Author: Volkan Yazıcı <vo...@yazi.ci>
AuthorDate: Wed Jan 17 16:01:19 2024 +0100
Remove ineffective tests
---
.../org/apache/log4j/defaultInit/TestCase1.java | 50 ---
.../org/apache/log4j/defaultInit/TestCase2.java | 55 ---
.../org/apache/log4j/defaultInit/TestCase3.java | 50 ---
.../org/apache/log4j/defaultInit/TestCase4.java | 56 ---
.../log4j/helpers/OptionConverterTestCase.java | 169 --------
.../log4j/helpers/PatternParserTestCase.java | 129 ------
.../java/org/apache/log4j/xml/DOMTestCase.java | 184 ---------
.../config/yaml/MultipleTriggeringPolicyTest.java | 9 -
log4j-core-its/pom.xml | 207 ----------
.../logging/log4j/FilterPerformanceComparison.java | 216 ----------
.../logging/log4j/PerformanceComparison.java | 198 ---------
.../org/apache/logging/log4j/PerformanceRun.java | 134 ------
.../apache/logging/log4j/core/SimplePerfTest.java | 196 ---------
.../logging/log4j/core/ThreadedPerfTest.java | 85 ----
.../apache/logging/log4j/core/ThreadedTest.java | 141 -------
.../log4j/core/appender/HttpAppenderTest.java | 336 ----------------
.../SecureSocketAppenderSocketOptionsTest.java | 140 -------
.../appender/SocketAppenderBufferSizeTest.java | 76 ----
.../appender/SocketAppenderSocketOptionsTest.java | 95 -----
.../log4j/core/appender/SocketAppenderTest.java | 447 ---------------------
.../core/async/perftest/AbstractRunQueue.java | 79 ----
.../log4j/core/async/perftest/Histogram.java | 344 ----------------
.../log4j/core/async/perftest/IPerfTestRunner.java | 32 --
.../log4j/core/async/perftest/IdleStrategy.java | 37 --
.../core/async/perftest/MultiThreadPerfTest.java | 105 -----
.../core/async/perftest/NoOpIdleStrategy.java | 35 --
.../log4j/core/async/perftest/PerfTest.java | 216 ----------
.../log4j/core/async/perftest/PerfTestDriver.java | 386 ------------------
.../async/perftest/PerfTestResultFormatter.java | 180 ---------
.../core/async/perftest/ResponseTimeTest.java | 410 -------------------
.../log4j/core/async/perftest/RunConversant.java | 30 --
.../log4j/core/async/perftest/RunJCTools.java | 30 --
.../log4j/core/async/perftest/RunLog4j1.java | 68 ----
.../log4j/core/async/perftest/RunLog4j2.java | 68 ----
.../log4j/core/async/perftest/RunLogback.java | 68 ----
.../log4j/core/async/perftest/SimplePerfTest.java | 141 -------
.../core/async/perftest/YieldIdleStrategy.java | 32 --
log4j-core-its/src/test/resources/logback-test.xml | 29 --
.../logging/log4j/core/CollectionLoggingTest.java | 78 ----
.../apache/logging/log4j/core/LogEventTest.java | 84 ----
.../log4j/core/appender/FileAppenderTest.java | 65 ---
...ollingRandomAccessFileAppenderRolloverTest.java | 105 -----
.../rolling/RollingAppenderCronOnceADayTest.java | 110 -----
.../RollingDirectSizeTimeNewDirectoryTest.java | 101 -----
...ingRandomAccessFileManagerHeaderFooterTest.java | 110 -----
.../logging/log4j/core/async/AsyncLoggerTest.java | 8 -
...WaitStrategyFactoryConfigGlobalLoggersTest.java | 58 ---
...eueFullAsyncLoggerLoggingFromToStringTest2.java | 41 --
.../log4j/core/config/xml/XmlSchemaTest.java | 105 -----
.../log4j/core/net/ssl/StoreConfigurationTest.java | 10 +-
.../apache/logging/log4j/core/util/InitTest.java | 43 --
...ncWaitStrategyFactoryConfigGlobalLoggerTest.xml | 32 --
.../src/test/resources/HttpAppenderTest.xml | 29 --
...ingRandomAccessFileAppenderHeaderFooterTest.xml | 38 --
.../src/test/resources/log4j-collectionLogging.xml | 38 --
.../log4j/layout/template/json/EcsLayoutTest.java | 3 +-
.../log4j/layout/template/json/LogstashIT.java | 3 +-
.../log4j/perf/jmh/AsyncLoggersBenchmark.java | 37 --
pom.xml | 1 -
59 files changed, 8 insertions(+), 6354 deletions(-)
diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/defaultInit/TestCase1.java b/log4j-1.2-api/src/test/java/org/apache/log4j/defaultInit/TestCase1.java
deleted file mode 100644
index 30aeafeb7a..0000000000
--- a/log4j-1.2-api/src/test/java/org/apache/log4j/defaultInit/TestCase1.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.log4j.defaultInit;
-
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-import org.apache.log4j.LogManager;
-import org.apache.log4j.Logger;
-import org.junit.Ignore;
-
-@Ignore
-public class TestCase1 extends TestCase {
-
- public TestCase1(final String name) {
- super(name);
- }
-
- public void setUp() {}
-
- public void tearDown() {
- LogManager.shutdown();
- }
-
- public void noneTest() {
- final Logger root = Logger.getRootLogger();
- final boolean rootIsConfigured = root.getAllAppenders().hasMoreElements();
- assertTrue(!rootIsConfigured);
- }
-
- public static Test suite() {
- final TestSuite suite = new TestSuite();
- suite.addTest(new TestCase1("noneTest"));
- return suite;
- }
-}
diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/defaultInit/TestCase2.java b/log4j-1.2-api/src/test/java/org/apache/log4j/defaultInit/TestCase2.java
deleted file mode 100644
index c41634fb1e..0000000000
--- a/log4j-1.2-api/src/test/java/org/apache/log4j/defaultInit/TestCase2.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.log4j.defaultInit;
-
-import java.util.Enumeration;
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-import org.apache.log4j.Appender;
-import org.apache.log4j.LogManager;
-import org.apache.log4j.Logger;
-import org.junit.Ignore;
-
-@Ignore
-public class TestCase2 extends TestCase {
-
- public TestCase2(final String name) {
- super(name);
- }
-
- public void setUp() {}
-
- public void tearDown() {
- LogManager.shutdown();
- }
-
- public void xmlTest() {
- final Logger root = Logger.getRootLogger();
- final boolean rootIsConfigured = root.getAllAppenders().hasMoreElements();
- assertTrue(rootIsConfigured);
- final Enumeration e = root.getAllAppenders();
- final Appender appender = (Appender) e.nextElement();
- assertEquals(appender.getName(), "D1");
- }
-
- public static Test suite() {
- final TestSuite suite = new TestSuite();
- suite.addTest(new TestCase2("xmlTest"));
- return suite;
- }
-}
diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/defaultInit/TestCase3.java b/log4j-1.2-api/src/test/java/org/apache/log4j/defaultInit/TestCase3.java
deleted file mode 100644
index 6978b7223a..0000000000
--- a/log4j-1.2-api/src/test/java/org/apache/log4j/defaultInit/TestCase3.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.log4j.defaultInit;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.IOException;
-import java.util.Enumeration;
-import org.apache.log4j.Appender;
-import org.apache.log4j.LogManager;
-import org.apache.log4j.Logger;
-import org.apache.log4j.config.TestConfigurator;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
-
-@Disabled
-public class TestCase3 {
-
- @AfterAll
- public static void tearDown() {
- LogManager.shutdown();
- }
-
- @Test
- public void propertiesTest() throws IOException {
- TestConfigurator.configure("src/test/resources/log4j1-1.2.17/input/defaultInit3.properties");
- final Logger root = Logger.getRootLogger();
- final boolean rootIsConfigured = root.getAllAppenders().hasMoreElements();
- assertTrue(rootIsConfigured);
- final Enumeration e = root.getAllAppenders();
- final Appender appender = (Appender) e.nextElement();
- assertEquals(appender.getName(), "D3");
- }
-}
diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/defaultInit/TestCase4.java b/log4j-1.2-api/src/test/java/org/apache/log4j/defaultInit/TestCase4.java
deleted file mode 100644
index 7bf4364faa..0000000000
--- a/log4j-1.2-api/src/test/java/org/apache/log4j/defaultInit/TestCase4.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.log4j.defaultInit;
-
-import java.util.Enumeration;
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-import org.apache.log4j.Appender;
-import org.apache.log4j.LogManager;
-import org.apache.log4j.Logger;
-import org.junit.Ignore;
-
-@Ignore
-public class TestCase4 extends TestCase {
-
- public TestCase4(final String name) {
- super(name);
- }
-
- public void setUp() {}
-
- public void tearDown() {
- LogManager.shutdown();
- }
-
- public void combinedTest() {
- final Logger root = Logger.getRootLogger();
- final boolean rootIsConfigured = root.getAllAppenders().hasMoreElements();
- assertTrue(rootIsConfigured);
- final Enumeration e = root.getAllAppenders();
- final Appender appender = (Appender) e.nextElement();
- assertEquals(appender.getName(), "D1");
- assertEquals(e.hasMoreElements(), false);
- }
-
- public static Test suite() {
- final TestSuite suite = new TestSuite();
- suite.addTest(new TestCase4("combinedTest"));
- return suite;
- }
-}
diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/OptionConverterTestCase.java b/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/OptionConverterTestCase.java
deleted file mode 100644
index c2e29b7824..0000000000
--- a/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/OptionConverterTestCase.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.log4j.helpers;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.util.Properties;
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-import org.apache.log4j.Level;
-import org.apache.log4j.LogManager;
-import org.apache.log4j.PropertyConfiguratorTest;
-import org.apache.log4j.xml.XLevel;
-import org.junit.Ignore;
-
-/**
- * Test variable substitution code.
- *
- * @since 1.0
- */
-@Ignore("WIP")
-public class OptionConverterTestCase extends TestCase {
-
- Properties props;
-
- public OptionConverterTestCase(final String name) {
- super(name);
- }
-
- public void setUp() {
- props = new Properties();
- props.put("TOTO", "wonderful");
- props.put("key1", "value1");
- props.put("key2", "value2");
- // Log4J will NPE without this:
- props.put("line.separator", System.getProperty("line.separator"));
- // Log4J will throw an Error without this:
- props.put("java.home", System.getProperty("java.home"));
- System.setProperties(props);
- }
-
- public void tearDown() {
- props = null;
- LogManager.resetConfiguration();
- }
-
- public void varSubstTest1() {
- String r;
-
- r = OptionConverter.substVars("hello world.", null);
- assertEquals("hello world.", r);
-
- r = OptionConverter.substVars("hello ${TOTO} world.", null);
-
- assertEquals("hello wonderful world.", r);
- }
-
- public void varSubstTest2() {
- String r;
-
- r = OptionConverter.substVars("Test2 ${key1} mid ${key2} end.", null);
- assertEquals("Test2 value1 mid value2 end.", r);
- }
-
- public void varSubstTest3() {
- String r;
-
- r = OptionConverter.substVars("Test3 ${unset} mid ${key1} end.", null);
- assertEquals("Test3 mid value1 end.", r);
- }
-
- public void varSubstTest4() {
- final String val = "Test4 ${incomplete ";
- try {
- OptionConverter.substVars(val, null);
- } catch (IllegalArgumentException e) {
- final String errorMsg = e.getMessage();
- // System.out.println('['+errorMsg+']');
- assertEquals('"' + val + "\" has no closing brace. Opening brace at position 6.", errorMsg);
- }
- }
-
- public void varSubstTest5() {
- final Properties props = new Properties();
- props.put("p1", "x1");
- props.put("p2", "${p1}");
- final String res = OptionConverter.substVars("${p2}", props);
- System.out.println("Result is [" + res + "].");
- assertEquals(res, "x1");
- }
-
- /**
- * Tests configuring Log4J from an InputStream.
- *
- * @since 1.2.17
- */
- public void testInputStream() throws IOException {
- final File file = new File("src/test/resources/log4j1-1.2.17/input/filter1.properties");
- assertTrue(file.exists());
- try (final FileInputStream inputStream = new FileInputStream(file)) {
- OptionConverter.selectAndConfigure(inputStream, null, LogManager.getLoggerRepository());
- }
- new PropertyConfiguratorTest().validateNested();
- }
-
- public void toLevelTest1() {
- final String val = "INFO";
- final Level p = OptionConverter.toLevel(val, null);
- assertEquals(p, Level.INFO);
- }
-
- public void toLevelTest2() {
- final String val = "INFO#org.apache.log4j.xml.XLevel";
- final Level p = OptionConverter.toLevel(val, null);
- assertEquals(p, Level.INFO);
- }
-
- public void toLevelTest3() {
- final String val = "TRACE#org.apache.log4j.xml.XLevel";
- final Level p = OptionConverter.toLevel(val, null);
- assertEquals(p, XLevel.TRACE);
- }
-
- public void toLevelTest4() {
- final String val = "TR#org.apache.log4j.xml.XLevel";
- final Level p = OptionConverter.toLevel(val, null);
- assertEquals(p, null);
- }
-
- public void toLevelTest5() {
- final String val = "INFO#org.apache.log4j.xml.TOTO";
- final Level p = OptionConverter.toLevel(val, null);
- assertEquals(p, null);
- }
-
- public static Test suite() {
- final TestSuite suite = new TestSuite();
- suite.addTest(new OptionConverterTestCase("varSubstTest5"));
- suite.addTest(new OptionConverterTestCase("varSubstTest1"));
- suite.addTest(new OptionConverterTestCase("varSubstTest2"));
- suite.addTest(new OptionConverterTestCase("varSubstTest3"));
- suite.addTest(new OptionConverterTestCase("varSubstTest4"));
-
- suite.addTest(new OptionConverterTestCase("testInputStream"));
-
- suite.addTest(new OptionConverterTestCase("toLevelTest1"));
- suite.addTest(new OptionConverterTestCase("toLevelTest2"));
- suite.addTest(new OptionConverterTestCase("toLevelTest3"));
- suite.addTest(new OptionConverterTestCase("toLevelTest4"));
- suite.addTest(new OptionConverterTestCase("toLevelTest5"));
- return suite;
- }
-}
diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/PatternParserTestCase.java b/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/PatternParserTestCase.java
deleted file mode 100644
index 83587139e3..0000000000
--- a/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/PatternParserTestCase.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.log4j.helpers;
-
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-import org.apache.log4j.Appender;
-import org.apache.log4j.FileAppender;
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-import org.apache.log4j.MDC;
-import org.apache.log4j.PatternLayout;
-import org.apache.log4j.util.Compare;
-import org.junit.Ignore;
-
-/**
- * Test case for helpers/PatternParser.java. Tests the various conversion patterns supported by PatternParser. This test
- * class tests PatternParser via the PatternLayout class which uses it.
- */
-@Ignore("WIP")
-public class PatternParserTestCase extends TestCase {
-
- static String OUTPUT_FILE = "target/PatternParser";
- static String WITNESS_FILE = "target/witness/PatternParser";
-
- static String msgPattern = "%m%n";
-
- public static Test suite() {
- final TestSuite suite = new TestSuite();
- suite.addTest(new PatternParserTestCase("mdcPattern"));
- return suite;
- }
-
- Logger root;
-
- Logger logger;
-
- public PatternParserTestCase(final String name) {
- super(name);
- }
-
- /**
- * Test case for MDC conversion pattern.
- */
- public void mdcPattern() throws Exception {
-
- final String mdcMsgPattern1 = "%m : %X%n";
- final String mdcMsgPattern2 = "%m : %X{key1}%n";
- final String mdcMsgPattern3 = "%m : %X{key2}%n";
- final String mdcMsgPattern4 = "%m : %X{key3}%n";
- final String mdcMsgPattern5 = "%m : %X{key1},%X{key2},%X{key3}%n";
-
- // set up appender
- final PatternLayout layout = new PatternLayout(msgPattern);
- final Appender appender = new FileAppender(layout, OUTPUT_FILE + "_mdc", false);
-
- // set appender on root and set level to debug
- root.addAppender(appender);
- root.setLevel(Level.DEBUG);
-
- // output starting message
- root.debug("starting mdc pattern test");
-
- layout.setConversionPattern(mdcMsgPattern1);
- root.debug("empty mdc, no key specified in pattern");
-
- layout.setConversionPattern(mdcMsgPattern2);
- root.debug("empty mdc, key1 in pattern");
-
- layout.setConversionPattern(mdcMsgPattern3);
- root.debug("empty mdc, key2 in pattern");
-
- layout.setConversionPattern(mdcMsgPattern4);
- root.debug("empty mdc, key3 in pattern");
-
- layout.setConversionPattern(mdcMsgPattern5);
- root.debug("empty mdc, key1, key2, and key3 in pattern");
-
- MDC.put("key1", "value1");
- MDC.put("key2", "value2");
-
- layout.setConversionPattern(mdcMsgPattern1);
- root.debug("filled mdc, no key specified in pattern");
-
- layout.setConversionPattern(mdcMsgPattern2);
- root.debug("filled mdc, key1 in pattern");
-
- layout.setConversionPattern(mdcMsgPattern3);
- root.debug("filled mdc, key2 in pattern");
-
- layout.setConversionPattern(mdcMsgPattern4);
- root.debug("filled mdc, key3 in pattern");
-
- layout.setConversionPattern(mdcMsgPattern5);
- root.debug("filled mdc, key1, key2, and key3 in pattern");
-
- MDC.remove("key1");
- MDC.remove("key2");
-
- layout.setConversionPattern(msgPattern);
- root.debug("finished mdc pattern test");
-
- assertTrue(Compare.compare(OUTPUT_FILE + "_mdc", WITNESS_FILE + "_mdc"));
- }
-
- public void setUp() {
- root = Logger.getRootLogger();
- root.removeAllAppenders();
- }
-
- public void tearDown() {
- root.getLoggerRepository().resetConfiguration();
- }
-}
diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/xml/DOMTestCase.java b/log4j-1.2-api/src/test/java/org/apache/log4j/xml/DOMTestCase.java
index 5f852e3302..63fca289ce 100644
--- a/log4j-1.2-api/src/test/java/org/apache/log4j/xml/DOMTestCase.java
+++ b/log4j-1.2-api/src/test/java/org/apache/log4j/xml/DOMTestCase.java
@@ -32,7 +32,6 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
-import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.VectorAppender;
@@ -43,17 +42,8 @@ import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.OptionHandler;
import org.apache.log4j.spi.ThrowableRenderer;
import org.apache.log4j.spi.ThrowableRendererSupport;
-import org.apache.log4j.util.Compare;
-import org.apache.log4j.util.ControlFilter;
-import org.apache.log4j.util.Filter;
-import org.apache.log4j.util.ISO8601Filter;
-import org.apache.log4j.util.JunitTestRunnerFilter;
-import org.apache.log4j.util.LineNumberFilter;
-import org.apache.log4j.util.SunReflectFilter;
-import org.apache.log4j.util.Transformer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
public class DOMTestCase {
@@ -171,20 +161,6 @@ public class DOMTestCase {
}
}
- static String TEMP_A1 = "target/output/temp.A1";
- static String TEMP_A2 = "target/output/temp.A2";
- static String FILTERED_A1 = "target/output/filtered.A1";
- static String FILTERED_A2 = "target/output/filtered.A2";
- static String EXCEPTION1 = "java.lang.Exception: Just testing";
- static String EXCEPTION2 = "\\s*at .*\\(.*\\)";
- static String EXCEPTION3 = "\\s*at .*\\(Native Method\\)";
- static String EXCEPTION4 = "\\s*at .*\\(.*Compiled Code\\)";
- static String EXCEPTION5 = "\\s*at .*\\(.*libgcj.*\\)";
- static String TEST1_1A_PAT = "(TRACE|DEBUG|INFO |WARN |ERROR|FATAL) \\w*\\.\\w* - Message \\d";
- static String TEST1_1B_PAT = "(TRACE|DEBUG|INFO |WARN |ERROR|FATAL) root - Message \\d";
- static String TEST1_2_PAT = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3} "
- + "\\[main]\\ (TRACE|DEBUG|INFO|WARN|ERROR|FATAL) .* - Message \\d";
-
private static final boolean Log4j1ActualAppender = false;
private static final boolean AssumeThrowableRendererSupport = false;
@@ -193,40 +169,6 @@ public class DOMTestCase {
Logger logger;
- void common() {
- final String oldThreadName = Thread.currentThread().getName();
- Thread.currentThread().setName("main");
-
- int i = -1;
-
- logger.trace("Message " + ++i);
- root.trace("Message " + i);
-
- logger.debug("Message " + ++i);
- root.debug("Message " + i);
-
- logger.info("Message " + ++i);
- root.info("Message " + i);
-
- logger.warn("Message " + ++i);
- root.warn("Message " + i);
-
- logger.error("Message " + ++i);
- root.error("Message " + i);
-
- logger.log(Level.FATAL, "Message " + ++i);
- root.log(Level.FATAL, "Message " + i);
-
- final Exception e = new Exception("Just testing");
- logger.debug("Message " + ++i, e);
- root.debug("Message " + i, e);
-
- logger.error("Message " + ++i, e);
- root.error("Message " + i, e);
-
- Thread.currentThread().setName(oldThreadName);
- }
-
@BeforeEach
public void setUp() {
root = Logger.getRootLogger();
@@ -238,105 +180,6 @@ public class DOMTestCase {
root.getLoggerRepository().resetConfiguration();
}
- @Test
- @Disabled
- public void test1() throws Exception {
- DOMConfigurator.configure("src/test/resources/log4j1-1.2.17/input/xml/DOMTestCase1.xml");
- common();
-
- final ControlFilter cf1 = new ControlFilter(
- new String[] {TEST1_1A_PAT, TEST1_1B_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});
-
- final ControlFilter cf2 = new ControlFilter(
- new String[] {TEST1_2_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});
-
- Transformer.transform(TEMP_A1, FILTERED_A1, new Filter[] {
- cf1, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter()
- });
-
- Transformer.transform(TEMP_A2, FILTERED_A2, new Filter[] {
- cf2, new LineNumberFilter(), new ISO8601Filter(), new SunReflectFilter(), new JunitTestRunnerFilter()
- });
-
- assertTrue(Compare.compare(FILTERED_A1, "witness/dom.A1.1"));
- assertTrue(Compare.compare(FILTERED_A2, "witness/dom.A2.1"));
- }
-
- /**
- * Tests processing of external entities in XML file.
- */
- @Test
- @Disabled
- public void test4() throws Exception {
- DOMConfigurator.configure("src/test/resources/log4j1-1.2.17/input/xml/DOMTest4.xml");
- common();
-
- final ControlFilter cf1 = new ControlFilter(
- new String[] {TEST1_1A_PAT, TEST1_1B_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});
-
- final ControlFilter cf2 = new ControlFilter(
- new String[] {TEST1_2_PAT, EXCEPTION1, EXCEPTION2, EXCEPTION3, EXCEPTION4, EXCEPTION5});
-
- Transformer.transform(TEMP_A1 + ".4", FILTERED_A1 + ".4", new Filter[] {
- cf1, new LineNumberFilter(), new SunReflectFilter(), new JunitTestRunnerFilter()
- });
-
- Transformer.transform(TEMP_A2 + ".4", FILTERED_A2 + ".4", new Filter[] {
- cf2, new LineNumberFilter(), new ISO8601Filter(), new SunReflectFilter(), new JunitTestRunnerFilter()
- });
-
- assertTrue(Compare.compare(FILTERED_A1 + ".4", "witness/dom.A1.4"));
- assertTrue(Compare.compare(FILTERED_A2 + ".4", "witness/dom.A2.4"));
- }
-
- /**
- * Tests that loggers mentioned in logger elements use the specified categoryFactory. See bug 33708.
- */
- @Test
- @Disabled
- public void testCategoryFactory1() {
- DOMConfigurator.configure("src/test/resources/log4j1-1.2.17/input/xml/categoryfactory1.xml");
- //
- // logger not explicitly mentioned in configuration,
- // should use default factory
- final Logger logger2 = Logger.getLogger("org.apache.log4j.xml.DOMTestCase.testCategoryFactory1.2");
- assertFalse(logger2.toString(), logger2 instanceof CustomLogger);
- //
- // logger explicitly mentioned in configuration,
- // should be a CustomLogger
- final Logger logger1 = Logger.getLogger("org.apache.log4j.xml.DOMTestCase.testCategoryFactory1.1");
- assertTrue(logger1.toString(), logger1 instanceof CustomLogger);
- //
- // logger not explicitly mentioned in configuration,
- // should use default factory
- final Logger logger2Bis = Logger.getLogger("org.apache.log4j.xml.DOMTestCase.testCategoryFactory1.2");
- assertFalse(logger2Bis.toString(), logger2Bis instanceof CustomLogger);
- }
-
- /**
- * Tests that loggers mentioned in logger-ref elements use the specified categoryFactory. See bug 33708.
- */
- @Test
- @Disabled
- public void testCategoryFactory2() {
- DOMConfigurator.configure("src/test/resources/log4j1-1.2.17/input/xml/categoryfactory2.xml");
- //
- // logger not explicitly mentioned in configuration,
- // should use default factory
- final Logger logger2 = Logger.getLogger("org.apache.log4j.xml.DOMTestCase.testCategoryFactory2.2");
- assertFalse(logger2.toString(), logger2 instanceof CustomLogger);
- //
- // logger explicitly mentioned in configuration,
- // should be a CustomLogger
- final Logger logger1 = Logger.getLogger("org.apache.log4j.xml.DOMTestCase.testCategoryFactory2.1");
- assertTrue(logger1.toString(), logger1 instanceof CustomLogger);
- //
- // logger not explicitly mentioned in configuration,
- // should use default factory
- final Logger logger2Bis = Logger.getLogger("org.apache.log4j.xml.DOMTestCase.testCategoryFactory2.2");
- assertFalse(logger2Bis.toString(), logger2Bis instanceof CustomLogger);
- }
-
/**
* Test checks that configureAndWatch does initial configuration, see bug 33502.
*
@@ -377,33 +220,6 @@ public class DOMTestCase {
assertFalse(configJar.exists());
}
- /**
- * Tests that loggers mentioned in logger elements use the specified loggerFactory. See bug 33708.
- */
- @Test
- @Disabled("TODO")
- public void testLoggerFactory1() {
- DOMConfigurator.configure("src/test/resources/log4j1-1.2.17/input/xml/loggerfactory1.xml");
- //
- // logger not explicitly mentioned in configuration,
- // should use default factory
- final Logger logger2 = Logger.getLogger("org.apache.log4j.xml.DOMTestCase.testLoggerFactory1.2");
- assertNotNull(logger2);
- assertFalse(logger2.toString(), logger2 instanceof CustomLogger);
- //
- // logger explicitly mentioned in configuration,
- // should be a CustomLogger
- final Logger logger1 = Logger.getLogger("org.apache.log4j.xml.DOMTestCase.testLoggerFactory1.1");
- assertNotNull(logger1);
- assertTrue(logger1.toString(), logger1 instanceof CustomLogger);
- //
- // logger not explicitly mentioned in configuration,
- // should use default factory
- final Logger logger2Bis = Logger.getLogger("org.apache.log4j.xml.DOMTestCase.testLoggerFactory1.2");
- assertNotNull(logger2Bis);
- assertFalse(logger2Bis.toString(), logger2Bis instanceof CustomLogger);
- }
-
/**
* This test checks that the subst method of an extending class is checked when evaluating parameters. See bug 43325.
*
diff --git a/log4j-config-yaml/src/test/java/org/apache/logging/log4j/config/yaml/MultipleTriggeringPolicyTest.java b/log4j-config-yaml/src/test/java/org/apache/logging/log4j/config/yaml/MultipleTriggeringPolicyTest.java
index 2d35516f3e..6d81adbded 100644
--- a/log4j-config-yaml/src/test/java/org/apache/logging/log4j/config/yaml/MultipleTriggeringPolicyTest.java
+++ b/log4j-config-yaml/src/test/java/org/apache/logging/log4j/config/yaml/MultipleTriggeringPolicyTest.java
@@ -26,7 +26,6 @@ import org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy;
import org.apache.logging.log4j.core.appender.rolling.TriggeringPolicy;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
-import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@@ -54,14 +53,6 @@ class MultipleTriggeringPolicyTest {
assertBothTriggeringPoliciesConfigured(configuration);
}
- @Test
- @Tag("yaml")
- @Disabled("LOG4J2-1100 demonstration")
- @LoggerContextSource("LOG4J2-1100/log4j2-good.yaml")
- void unsupportedYamlSyntax(final Configuration configuration) {
- assertBothTriggeringPoliciesConfigured(configuration);
- }
-
void assertBothTriggeringPoliciesConfigured(final Configuration configuration) {
final RollingFileAppender appender = configuration.getAppender("File");
assertNotNull(appender);
diff --git a/log4j-core-its/pom.xml b/log4j-core-its/pom.xml
deleted file mode 100644
index dc38a2f1eb..0000000000
--- a/log4j-core-its/pom.xml
+++ /dev/null
@@ -1,207 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one or more
- ~ contributor license agreements. See the NOTICE file distributed with
- ~ this work for additional information regarding copyright ownership.
- ~ The ASF licenses this file to you under the Apache License, Version 2.0
- ~ (the "License"); you may not use this file except in compliance with
- ~ the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.apache.logging.log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>${revision}</version>
- <relativePath>../log4j-parent</relativePath>
- </parent>
-
- <artifactId>log4j-core-its</artifactId>
- <packaging>jar</packaging>
- <name>Apache Log4j Core Integration Tests</name>
- <description>Integration Tests for the Apache Log4j Implementation</description>
- <properties>
- <docLabel>Core Documentation</docLabel>
- <projectDir>/core</projectDir>
- <bnd.baseline.skip>true</bnd.baseline.skip>
- <maven.deploy.skip>true</maven.deploy.skip>
- <maven.install.skip>true</maven.install.skip>
- <maven.test.skip>true</maven.test.skip>
- </properties>
- <dependencies>
- <!-- Alternative implementation of BlockingQueue using Conversant Disruptor for AsyncAppender -->
- <dependency>
- <groupId>com.conversantmedia</groupId>
- <artifactId>disruptor</artifactId>
- <optional>true</optional>
- </dependency>
- <!-- Required for AsyncLoggers -->
- <dependency>
- <groupId>com.lmax</groupId>
- <artifactId>disruptor</artifactId>
- <optional>true</optional>
- </dependency>
- <!-- Required for JSON support -->
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <optional>true</optional>
- </dependency>
- <!-- Required for JSON support -->
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <optional>true</optional>
- </dependency>
- <!-- Required for XML layout and receiver support -->
- <dependency>
- <groupId>com.fasterxml.jackson.dataformat</groupId>
- <artifactId>jackson-dataformat-xml</artifactId>
- <optional>true</optional>
- </dependency>
- <!-- Required for YAML support (including JSON requirements) -->
- <dependency>
- <groupId>com.fasterxml.jackson.dataformat</groupId>
- <artifactId>jackson-dataformat-yaml</artifactId>
- <optional>true</optional>
- </dependency>
- <dependency>
- <groupId>org.junit.jupiter</groupId>
- <artifactId>junit-jupiter-engine</artifactId>
- </dependency>
- <!-- JUnit, naturally -->
- <dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- </dependency>
- <!-- POM for jackson-dataformat-xml 2.9.2 depends on woodstox-core 5.0.3 -->
- <dependency>
- <groupId>com.fasterxml.woodstox</groupId>
- <artifactId>woodstox-core</artifactId>
- <optional>true</optional>
- </dependency>
- <dependency>
- <groupId>org.apache.logging.log4j</groupId>
- <artifactId>log4j-api</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.logging.log4j</groupId>
- <artifactId>log4j-api-test</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.logging.log4j</groupId>
- <artifactId>log4j-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.logging.log4j</groupId>
- <artifactId>log4j-core-test</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.logging.log4j</groupId>
- <artifactId>log4j-layout-template-json</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.logging.log4j</groupId>
- <artifactId>log4j-layout-jackson-xml</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.hamcrest</groupId>
- <artifactId>hamcrest</artifactId>
- <scope>test</scope>
- </dependency>
- <!-- TEST DEPENDENCIES -->
- <!-- Log4j 1.2 tests -->
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-classic</artifactId>
- <scope>test</scope>
- </dependency>
- <!-- Logback performance tests -->
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-core</artifactId>
- <scope>test</scope>
- </dependency>
- <!-- SLF4J tests -->
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <scope>test</scope>
- </dependency>
- <!-- Used for testing HttpAppender -->
- <dependency>
- <groupId>com.github.tomakehurst</groupId>
- <artifactId>wiremock-jre8</artifactId>
- <scope>test</scope>
- </dependency>
- <!-- For Async tests -->
- <dependency>
- <groupId>org.hdrhistogram</groupId>
- <artifactId>HdrHistogram</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
-
- <!--
- ~ Unban Logback.
- -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-enforcer-plugin</artifactId>
- <executions>
- <execution>
- <id>ban-logging-dependencies</id>
- <configuration>
- <rules>
- <bannedDependencies>
- <includes>
- <include>ch.qos.logback:*:*:*:test</include>
- </includes>
- </bannedDependencies>
- </rules>
- </configuration>
- </execution>
- </executions>
- </plugin>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-failsafe-plugin</artifactId>
- <configuration>
- <additionalClasspathElements>
- <additionalClasspathElement>${project.basedir}/src/test/resources</additionalClasspathElement>
- </additionalClasspathElements>
- <includes>
- <include>**/*.java</include>
- </includes>
- <excludes>
- <exclude>**/ForceNoDefClassFoundError.*</exclude>
- </excludes>
- <groups>org.apache.logging.log4j.core.test.categories.PerformanceTests</groups>
- </configuration>
- </plugin>
-
- </plugins>
- </build>
-</project>
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/FilterPerformanceComparison.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/FilterPerformanceComparison.java
deleted file mode 100644
index e0c9f08f28..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/FilterPerformanceComparison.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import org.apache.logging.log4j.core.impl.Log4jPropertyKey;
-import org.apache.logging.log4j.core.test.categories.PerformanceTests;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.slf4j.MDC;
-
-/**
- *
- */
-@Category(PerformanceTests.class)
-public class FilterPerformanceComparison {
-
- private final Logger logger = LogManager.getLogger(FilterPerformanceComparison.class.getName());
- private final org.slf4j.Logger logbacklogger = org.slf4j.LoggerFactory.getLogger(FilterPerformanceComparison.class);
-
- // How many times should we try to log:
- private static final int COUNT = 10000000;
- private static final int THREADED_COUNT = 100000;
- private static final int WARMUP = 1000;
-
- private static final String CONFIG = "log4j2-perf-filter.xml";
- private static final String LOGBACK_CONFIG = "logback-perf-filter.xml";
-
- private static final String LOGBACK_CONF = "logback.configurationFile";
-
- @BeforeClass
- public static void setupClass() {
- System.setProperty(Log4jPropertyKey.CONFIG_LOCATION.getSystemKey(), CONFIG);
- System.setProperty(LOGBACK_CONF, LOGBACK_CONFIG);
- }
-
- @AfterClass
- public static void cleanupClass() {
- System.clearProperty(Log4jPropertyKey.CONFIG_LOCATION.getSystemKey());
- System.clearProperty(LOGBACK_CONF);
- }
-
- @After
- public void after() {
- ThreadContext.clearAll();
- }
-
- @Test
- public void testPerformanceEmptyContext() throws Exception {
- testPerformance(Collections.<String, String>emptyMap());
- }
-
- @Test
- public void testPerformanceNonEmptyContext() throws Exception {
- testPerformance(createNonEmptyContextData());
- }
-
- private Map<String, String> createNonEmptyContextData() {
- final Map<String, String> context = new HashMap<>();
- context.put("user0", "Apache");
- context.put("user1", "Apache");
- return context;
- }
-
- private static void putContextData(final Map<String, String> contextData) {
- ThreadContext.putAll(contextData);
- for (final Map.Entry<String, String> entry : contextData.entrySet()) {
- MDC.put(entry.getKey(), entry.getValue());
- }
- }
-
- private void testPerformance(final Map<String, String> contextData) throws Exception {
- putContextData(contextData);
- Target.LOGBACK.timedLoop(logger, logbacklogger, WARMUP);
- Target.LOG4J2.timedLoop(logger, logbacklogger, WARMUP);
-
- System.out.println(
- "Single-threaded Log4j 2.0, " + (contextData.isEmpty() ? "EMPTY context" : "NON-EMPTY context"));
-
- final long result3 = Target.LOG4J2.timedLoop(logger, logbacklogger, COUNT);
- System.out.println(
- "Single-threaded Logback, " + (contextData.isEmpty() ? "EMPTY context" : "NON-EMPTY context"));
-
- final long result2 = Target.LOGBACK.timedLoop(logger, logbacklogger, COUNT);
-
- System.out.println("###############################################");
- System.out.println("Logback: " + result2);
- System.out.println("Log4j 2.0: " + result3);
- System.out.println("###############################################");
- }
-
- @Test
- public void testThreadsEmptyContext() throws Exception {
- testThreads(Collections.<String, String>emptyMap());
- }
-
- @Test
- public void testThreadsNonEmptyContext() throws Exception {
- testThreads(createNonEmptyContextData());
- }
-
- private void testThreads(final Map<String, String> contextData) throws Exception {
- System.out.println("Testing multithreading");
- final int threadedCount = COUNT; // THREADED_COUNT * threadCount < COUNT ? COUNT / threadCount : THREADED_COUNT;
- final int[] threadCounts = new int[] {1, 2, 5, 10, 20, 50};
- for (final int threadCount : threadCounts) {
- System.out.println("Testing " + threadCount + " threads, "
- + (contextData.isEmpty() ? "EMPTY context" : "NON-EMPTY context"));
- final Worker[] workers = new Worker[threadCount];
- final long[] results = new long[threadCount];
- for (int i = 0; i < threadCount; ++i) {
- workers[i] = new Worker(Target.LOG4J2, threadedCount, results, i, contextData);
- }
- for (int i = 0; i < threadCount; ++i) {
- workers[i].start();
- }
- long total = 0;
- for (int i = 0; i < threadCount; ++i) {
- workers[i].join();
- total += results[i];
- }
- final long result3 = total / threadCount;
- total = 0;
- for (int i = 0; i < threadCount; ++i) {
- workers[i] = new Worker(Target.LOGBACK, threadedCount, results, i, contextData);
- }
- for (int i = 0; i < threadCount; ++i) {
- workers[i].start();
- }
- for (int i = 0; i < threadCount; ++i) {
- workers[i].join();
- total += results[i];
- }
- final long result2 = total / threadCount;
- System.out.println("###############################################");
- System.out.println("Logback: " + result2);
- System.out.println("Log4j 2.0: " + result3);
- System.out.println("###############################################");
- }
- }
-
- private enum Target {
- LOGBACK {
- @Override
- long timedLoop(final Logger logger, final org.slf4j.Logger logbacklogger, final int loop) {
- final Integer j = Integer.valueOf(2);
- final long start = System.nanoTime();
- for (int i = 0; i < loop; i++) {
- logbacklogger.debug("SEE IF THIS IS LOGGED {}.", j);
- }
- return (System.nanoTime() - start) / loop;
- }
- },
-
- LOG4J2 {
- @Override
- long timedLoop(final Logger logger, final org.slf4j.Logger logbacklogger, final int loop) {
- final Integer j = Integer.valueOf(2);
- final long start = System.nanoTime();
- for (int i = 0; i < loop; i++) {
- logger.debug("SEE IF THIS IS LOGGED {}.", j);
- }
- return (System.nanoTime() - start) / loop;
- }
- };
-
- abstract long timedLoop(final Logger logger, final org.slf4j.Logger logbacklogger, final int loop);
- }
-
- private class Worker extends Thread {
-
- private final Target target;
- private final int count;
- private final long[] results;
- private final int index;
- private final Map<String, String> contextData;
-
- public Worker(
- final Target target,
- final int count,
- final long[] results,
- final int index,
- final Map<String, String> contextData) {
- this.target = target;
- this.count = count;
- this.results = results;
- this.index = index;
- this.contextData = contextData;
- }
-
- @Override
- public void run() {
- putContextData(contextData);
- results[index] = target.timedLoop(logger, logbacklogger, count);
- }
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/PerformanceComparison.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/PerformanceComparison.java
deleted file mode 100644
index 6787c07260..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/PerformanceComparison.java
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j;
-
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.OutputStream;
-import java.io.Writer;
-import java.nio.ByteBuffer;
-import java.nio.channels.FileChannel;
-import org.apache.logging.log4j.core.impl.Log4jPropertyKey;
-import org.apache.logging.log4j.core.test.categories.PerformanceTests;
-import org.apache.logging.log4j.core.test.util.Profiler;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-/**
- * Use this class to analyze performance between Log4j and other logging frameworks.
- */
-@Category(PerformanceTests.class)
-public class PerformanceComparison {
-
- private final Logger logger = LogManager.getLogger(PerformanceComparison.class.getName());
- private final org.slf4j.Logger logbacklogger = org.slf4j.LoggerFactory.getLogger(PerformanceComparison.class);
- private final org.apache.log4j.Logger log4jlogger = org.apache.log4j.Logger.getLogger(PerformanceComparison.class);
-
- // How many times should we try to log:
- private static final int COUNT = 500000;
- private static final int PROFILE_COUNT = 500000;
- private static final int WARMUP = 50000;
-
- private static final String CONFIG = "log4j2-perf.xml";
- private static final String LOGBACK_CONFIG = "logback-perf.xml";
- private static final String LOG4J_CONFIG = "log4j12-perf.xml";
-
- private static final String LOGBACK_CONF = "logback.configurationFile";
- private static final String LOG4J_CONF = "log4j.configuration";
-
- @BeforeClass
- public static void setupClass() {
- System.setProperty(Log4jPropertyKey.CONFIG_LOCATION.getSystemKey(), CONFIG);
- System.setProperty(LOGBACK_CONF, LOGBACK_CONFIG);
- System.setProperty(LOG4J_CONF, LOG4J_CONFIG);
- }
-
- @AfterClass
- public static void cleanupClass() {
- System.clearProperty(Log4jPropertyKey.CONFIG_LOCATION.getSystemKey());
- 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();
- }
-
- @Test
- public void testPerformance() throws Exception {
-
- log4j(WARMUP);
- logback(WARMUP);
- log4j2(WARMUP);
-
- if (Profiler.isActive()) {
- System.out.println("Profiling Log4j 2.0");
- Profiler.start();
- final long result = log4j2(PROFILE_COUNT);
- Profiler.stop();
- System.out.println("###############################################");
- System.out.println("Log4j 2.0: " + result);
- System.out.println("###############################################");
- } else {
- doRun();
- doRun();
- doRun();
- doRun();
- }
- }
-
- private void doRun() {
- System.out.print("Log4j : ");
- System.out.println(log4j(COUNT));
-
- System.out.print("Logback : ");
- System.out.println(logback(COUNT));
-
- System.out.print("Log4j 2.0: ");
- System.out.println(log4j2(COUNT));
-
- System.out.println("###############################################");
- }
-
- // @Test
- private void testRawPerformance() throws Exception {
- final OutputStream os = new FileOutputStream("target/testos.log", true);
- final long result1 = writeToStream(COUNT, os);
- os.close();
- final OutputStream bos = new BufferedOutputStream(new FileOutputStream("target/testbuffer.log", true));
- final long result2 = writeToStream(COUNT, bos);
- bos.close();
- final Writer w = new FileWriter("target/testwriter.log", true);
- final long result3 = writeToWriter(COUNT, w);
- w.close();
- final FileOutputStream cos = new FileOutputStream("target/testchannel.log", true);
- final FileChannel channel = cos.getChannel();
- final long result4 = writeToChannel(COUNT, channel);
- cos.close();
- System.out.println("###############################################");
- System.out.println("FileOutputStream: " + result1);
- System.out.println("BufferedOutputStream: " + result2);
- System.out.println("FileWriter: " + result3);
- System.out.println("FileChannel: " + result4);
- System.out.println("###############################################");
- }
-
- private long log4j(final int loop) {
- final Integer j = Integer.valueOf(2);
- final long start = System.nanoTime();
- for (int i = 0; i < loop; i++) {
- log4jlogger.debug("SEE IF THIS IS LOGGED " + j + '.');
- }
- return (System.nanoTime() - start) / loop;
- }
-
- private long logback(final int loop) {
- final Integer j = Integer.valueOf(2);
- final long start = System.nanoTime();
- for (int i = 0; i < loop; i++) {
- logbacklogger.debug("SEE IF THIS IS LOGGED " + j + '.');
- }
- return (System.nanoTime() - start) / loop;
- }
-
- private long log4j2(final int loop) {
- final Integer j = Integer.valueOf(2);
- final long start = System.nanoTime();
- for (int i = 0; i < loop; i++) {
- logger.debug("SEE IF THIS IS LOGGED " + j + '.');
- }
- return (System.nanoTime() - start) / loop;
- }
-
- private long writeToWriter(final int loop, final Writer w) throws Exception {
- final Integer j = Integer.valueOf(2);
- final long start = System.nanoTime();
- for (int i = 0; i < loop; i++) {
- w.write("SEE IF THIS IS LOGGED " + j + '.');
- }
- return (System.nanoTime() - start) / loop;
- }
-
- private long writeToStream(final int loop, final OutputStream os) throws Exception {
- final Integer j = Integer.valueOf(2);
- final long start = System.nanoTime();
- for (int i = 0; i < loop; i++) {
- os.write(getBytes("SEE IF THIS IS LOGGED " + j + '.'));
- }
- return (System.nanoTime() - start) / loop;
- }
-
- private long writeToChannel(final int loop, final FileChannel channel) throws Exception {
- final Integer j = Integer.valueOf(2);
- final ByteBuffer buf = ByteBuffer.allocateDirect(8 * 1024);
- final long start = System.nanoTime();
- for (int i = 0; i < loop; i++) {
- channel.write(getByteBuffer(buf, "SEE IF THIS IS LOGGED " + j + '.'));
- }
- return (System.nanoTime() - start) / loop;
- }
-
- private ByteBuffer getByteBuffer(final ByteBuffer buf, final String s) {
- buf.clear();
- buf.put(s.getBytes());
- buf.flip();
- return buf;
- }
-
- private byte[] getBytes(final String s) {
- return s.getBytes();
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/PerformanceRun.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/PerformanceRun.java
deleted file mode 100644
index ac344b21dc..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/PerformanceRun.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j;
-
-import java.io.BufferedOutputStream;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.OutputStream;
-import java.io.Writer;
-import java.nio.ByteBuffer;
-import java.nio.channels.FileChannel;
-import org.apache.logging.log4j.core.test.categories.PerformanceTests;
-import org.apache.logging.log4j.core.test.junit.LoggerContextRule;
-import org.junit.ClassRule;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-/**
- * Use this class to analyze Log4j-only performance.
- * <p>
- * See {@linkplain PerformanceComparison} to compare performance with other logging frameworks.
- * </p>
- */
-@Category(PerformanceTests.class)
-public class PerformanceRun {
-
- private static final String CONFIG = "log4j2-perf.xml";
-
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
-
- private final Logger logger = context.getLogger(PerformanceRun.class.getName());
-
- // How many times should we try to log:
- private static final int COUNT = 1000000;
-
- @Test
- public void testPerformance() throws Exception {
- System.out.println("Starting Log4j 2.0");
- final long result3 = log4j2(COUNT);
-
- System.out.println("###############################################");
- System.out.println("Log4j 2.0: " + result3);
- System.out.println("###############################################");
- }
-
- @Test
- @Ignore("Why was this test disabled?")
- public void testRawPerformance() throws Exception {
- final OutputStream os = new FileOutputStream("target/testos.log", true);
- final long result1 = writeToStream(COUNT, os);
- os.close();
- final OutputStream bos = new BufferedOutputStream(new FileOutputStream("target/testbuffer.log", true));
- final long result2 = writeToStream(COUNT, bos);
- bos.close();
- final Writer w = new FileWriter("target/testwriter.log", true);
- final long result3 = writeToWriter(COUNT, w);
- w.close();
- final FileOutputStream cos = new FileOutputStream("target/testchannel.log", true);
- final FileChannel channel = cos.getChannel();
- final long result4 = writeToChannel(COUNT, channel);
- cos.close();
- System.out.println("###############################################");
- System.out.println("FileOutputStream: " + result1);
- System.out.println("BufferedOutputStream: " + result2);
- System.out.println("FileWriter: " + result3);
- System.out.println("FileChannel: " + result4);
- System.out.println("###############################################");
- }
-
- private long log4j2(final int loop) {
- final long start = System.nanoTime();
- for (int i = 0; i < loop; i++) {
- if (logger.isDebugEnabled()) {
- logger.debug("SEE IF THIS IS LOGGED");
- }
- }
- return (System.nanoTime() - start) / loop;
- }
-
- private long writeToWriter(final int loop, final Writer w) throws Exception {
- final Integer j = Integer.valueOf(2);
- final long start = System.nanoTime();
- for (int i = 0; i < loop; i++) {
- w.write("SEE IF THIS IS LOGGED " + j + '.');
- }
- return (System.nanoTime() - start) / loop;
- }
-
- private long writeToStream(final int loop, final OutputStream os) throws Exception {
- final Integer j = Integer.valueOf(2);
- final long start = System.nanoTime();
- for (int i = 0; i < loop; i++) {
- os.write(getBytes("SEE IF THIS IS LOGGED " + j + '.'));
- }
- return (System.nanoTime() - start) / loop;
- }
-
- private long writeToChannel(final int loop, final FileChannel channel) throws Exception {
- final Integer j = Integer.valueOf(2);
- final ByteBuffer buf = ByteBuffer.allocateDirect(8 * 1024);
- final long start = System.nanoTime();
- for (int i = 0; i < loop; i++) {
- channel.write(getByteBuffer(buf, "SEE IF THIS IS LOGGED " + j + '.'));
- }
- return (System.nanoTime() - start) / loop;
- }
-
- private ByteBuffer getByteBuffer(final ByteBuffer buf, final String s) {
- buf.clear();
- buf.put(s.getBytes());
- buf.flip();
- return buf;
- }
-
- private byte[] getBytes(final String s) {
- return s.getBytes();
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/SimplePerfTest.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/SimplePerfTest.java
deleted file mode 100644
index e722c4efcc..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/SimplePerfTest.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core;
-
-import java.util.Random;
-import org.apache.logging.log4j.Level;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.core.config.Configuration;
-import org.apache.logging.log4j.core.config.DefaultConfiguration;
-import org.apache.logging.log4j.test.Timer;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Tag;
-import org.junit.jupiter.api.Test;
-
-/**
- *
- */
-@Tag("sleepy")
-@Tag("performance")
-public class SimplePerfTest {
-
- private static org.apache.logging.log4j.Logger logger = LogManager.getLogger(SimplePerfTest.class.getName());
- private volatile Level lvl = Level.DEBUG;
- private static final int LOOP_CNT = 10000000;
- private static final int WARMUP = 1000;
- private static long maxTime;
- private static Random rand = new SimpleRandom();
- private static int RAND_SIZE = 250;
- private static int[] values = new int[RAND_SIZE];
-
- @BeforeAll
- public static void setupClass() {
-
- final Configuration config = LoggerContext.getContext().getConfiguration();
-
- if (!DefaultConfiguration.DEFAULT_NAME.equals(config.getName())) {
- System.out.println("Configuration was " + config.getName());
- LoggerContext.getContext().start(new DefaultConfiguration());
- }
-
- for (int i = 0; i < WARMUP; ++i) {
- overhead();
- }
- System.gc();
- final Timer timer = new Timer("Setup", LOOP_CNT);
- timer.start();
- for (int i = 0; i < (LOOP_CNT / 150); ++i) {
- overhead();
- }
- timer.stop();
- maxTime = timer.getElapsedNanoTime();
- System.gc();
- System.out.println(timer.toString());
- }
-
- @Test
- public void debugDisabled() throws Exception {
- long elapsed = 0;
- for (int retries = 1; retries <= 5; ++retries) {
- System.out.println("Iteration " + retries);
- System.gc();
- Thread.sleep(100);
- final Timer timer = new Timer("DebugDisabled", LOOP_CNT);
- timer.start();
- for (int i = 0; i < LOOP_CNT; ++i) {
- logger.isDebugEnabled();
- }
- timer.stop();
- System.out.println(timer.toString());
- elapsed = timer.getElapsedNanoTime();
- if (elapsed < maxTime) {
- break;
- }
- }
- Assertions.assertTrue(maxTime > elapsed, "Timer exceeded max time of " + maxTime);
- }
-
- @Test
- public void debugDisabledByLevel() throws Exception {
- long elapsed = 0;
- for (int retries = 1; retries <= 5; ++retries) {
- System.out.println("Iteration " + retries);
- System.gc();
- Thread.sleep(100);
- final Timer timer = new Timer("IsEnabled", LOOP_CNT);
- timer.start();
- for (int i = 0; i < LOOP_CNT; ++i) {
- logger.isEnabled(Level.DEBUG);
- }
- timer.stop();
- System.out.println(timer.toString());
- elapsed = timer.getElapsedNanoTime();
- if (elapsed < maxTime) {
- break;
- }
- }
- Assertions.assertTrue(maxTime > elapsed, "Timer exceeded max time of " + maxTime);
- }
-
- @Test
- public void debugLogger() throws Exception {
- long elapsed = 0;
- for (int retries = 1; retries <= 5; ++retries) {
- System.out.println("Iteration " + retries);
- System.gc();
- Thread.sleep(100);
- final Timer timer = new Timer("DebugLogger", LOOP_CNT);
- final String msg = "This is a test";
- timer.start();
- for (int i = 0; i < LOOP_CNT; ++i) {
- logger.debug(msg);
- }
- timer.stop();
- System.out.println(timer.toString());
- elapsed = timer.getElapsedNanoTime();
- if (elapsed < maxTime) {
- break;
- }
- }
- Assertions.assertTrue(maxTime > elapsed, "Timer exceeded max time of " + maxTime);
- }
- /*
- @Test
- public void errorLogger() {
- Timer timer = new Timer("ErrorLogger", 10);
- timer.start();
- for (int i=0; i < 10; ++i) {
- logger.error("This is a test");
- }
- timer.stop();
- System.out.println(timer.toString());
- } */
-
- /*
- * Try to generate some overhead that can't be optimized well. Not sure how accurate this is,
- * but the point is simply to insure that changes made don't suddenly cause performance issues.
- */
- private static void overhead() {
- final int values[] = new int[RAND_SIZE];
- final Random rand = new SimpleRandom();
-
- for (int i = 0; i < RAND_SIZE; ++i) {
- values[i] = rand.nextInt();
- }
- bubbleSort(values);
- }
-
- private static class SimpleRandom extends Random {
- /**
- * Generated serial version ID.
- */
- private static final long serialVersionUID = 3517002855516031846L;
-
- private int low = 5;
- private int high = 55;
-
- @Override
- public int nextInt() {
- high = 36969 * (high & 65535) + (high >> 16);
- low = 18000 * (low & 65535) + (low >> 16);
- return (high << 16) + low;
- }
- }
-
- /**
- * Standard BubbleSort algorithm.
- * @param array The array to sort.
- */
- private static void bubbleSort(final int array[]) {
- final int length = array.length;
- for (int i = 0; i < length; i++) {
- for (int j = 1; j < length - i; j++) {
- if (array[j - 1] > array[j]) {
- final int temp = array[j - 1];
- array[j - 1] = array[j];
- array[j] = temp;
- }
- }
- }
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/ThreadedPerfTest.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/ThreadedPerfTest.java
deleted file mode 100644
index 0317b64491..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/ThreadedPerfTest.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core;
-
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import org.apache.logging.log4j.Level;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.core.test.categories.PerformanceTests;
-import org.apache.logging.log4j.test.Timer;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-/**
- *
- */
-@Category(PerformanceTests.class)
-public class ThreadedPerfTest {
-
- private static final org.apache.logging.log4j.Logger logger =
- LogManager.getLogger(ThreadedPerfTest.class.getName());
- private volatile Level lvl = Level.DEBUG;
- private static final int LOOP_CNT = 10000000;
- private static final int THREADS = 10;
-
- @Test
- public void debugDisabled() {
- final Timer timer = new Timer("DebugDisabled", LOOP_CNT * THREADS);
- final Runnable runnable = new DebugDisabledRunnable();
- final ExecutorService pool = Executors.newFixedThreadPool(THREADS);
- timer.start();
- for (int i = 0; i < THREADS; ++i) {
- pool.execute(runnable);
- }
- pool.shutdown();
- timer.stop();
- System.out.println(timer.toString());
- }
-
- @Test
- public void debugLogger() {
- final Timer timer = new Timer("DebugLogger", LOOP_CNT * THREADS);
- final Runnable runnable = new DebugLoggerRunnable();
- final ExecutorService pool = Executors.newFixedThreadPool(THREADS);
- timer.start();
- for (int i = 0; i < THREADS; ++i) {
- pool.execute(runnable);
- }
- pool.shutdown();
- timer.stop();
- System.out.println(timer.toString());
- }
-
- public static class DebugDisabledRunnable implements Runnable {
- @Override
- public void run() {
- for (int i = 0; i < LOOP_CNT; ++i) {
- logger.isDebugEnabled();
- }
- }
- }
-
- public static class DebugLoggerRunnable implements Runnable {
- @Override
- public void run() {
- for (int i = 0; i < LOOP_CNT; ++i) {
- logger.debug("This is a test");
- }
- }
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/ThreadedTest.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/ThreadedTest.java
deleted file mode 100644
index b4a171f2c8..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/ThreadedTest.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core;
-
-import java.io.File;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.atomic.AtomicInteger;
-import org.apache.logging.log4j.Level;
-import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.core.test.categories.PerformanceTests;
-import org.apache.logging.log4j.core.test.junit.LoggerContextRule;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.junit.rules.RuleChain;
-import org.junit.rules.TestRule;
-import org.junit.runner.Description;
-import org.junit.runners.model.Statement;
-
-/**
- *
- */
-@Category(PerformanceTests.class)
-public class ThreadedTest {
- private static final String DIR = "target/threaded";
- private static final String CONFIG = "log4j-threaded.xml";
- private static final int LOOP_CNT = 25;
- private static final int THREADS = 4;
- private static final AtomicInteger counter = new AtomicInteger(0);
- private static final LoggerContextRule context = new LoggerContextRule(CONFIG);
-
- private final Logger logger = context.getLogger(ThreadedTest.class.getName());
- private volatile Level lvl = Level.DEBUG;
-
- // this would look pretty sweet with lambdas
- @ClassRule
- public static RuleChain chain = RuleChain.outerRule(new TestRule() {
- @Override
- public Statement apply(final Statement base, final Description description) {
- return new Statement() {
- @Override
- public void evaluate() throws Throwable {
- deleteDir();
- try {
- base.evaluate();
- } finally {
- deleteDir();
- }
- }
- };
- }
- })
- .around(context);
-
- @Test
- public void testDeadlock() throws Exception {
- final ExecutorService pool = Executors.newFixedThreadPool(THREADS * 2);
- final State state = new State();
- for (int count = 0; count < THREADS; ++count) {
- pool.execute(new LoggingRunnable(state));
- pool.execute(new StateSettingRunnable(state));
- }
- Thread.sleep(250);
- pool.shutdown();
- System.out.println("Counter = " + counter);
- }
-
- public class LoggingRunnable implements Runnable {
- private final State state;
-
- public LoggingRunnable(final State state) {
- this.state = state;
- }
-
- @Override
- public void run() {
- for (int i = 0; i < LOOP_CNT; ++i) {
- logger.debug(state);
- }
- }
- }
-
- public class StateSettingRunnable implements Runnable {
- private final State state;
-
- public StateSettingRunnable(final State state) {
- this.state = state;
- }
-
- @Override
- public void run() {
- for (int i = 0; i < LOOP_CNT * 4; ++i) {
- Thread.yield();
- state.setState();
- }
- }
- }
-
- private static void deleteDir() {
- final File dir = new File(DIR);
- if (dir.exists()) {
- final File[] files = dir.listFiles();
- for (final File file : files) {
- file.delete();
- }
- dir.delete();
- }
- }
-
- class State {
-
- synchronized void setState() {
- // Something takes a long time here
- logger.debug("hello world");
- }
-
- synchronized Object getState() {
- return counter.incrementAndGet();
- }
-
- @Override
- public String toString() {
- return "state=" + getState();
- }
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/appender/HttpAppenderTest.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/appender/HttpAppenderTest.java
deleted file mode 100644
index 1265c3a6df..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/appender/HttpAppenderTest.java
+++ /dev/null
@@ -1,336 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.appender;
-
-import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
-import static com.github.tomakehurst.wiremock.client.WireMock.containing;
-import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
-import static com.github.tomakehurst.wiremock.client.WireMock.post;
-import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
-import static com.github.tomakehurst.wiremock.client.WireMock.put;
-import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor;
-import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
-import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;
-import com.github.tomakehurst.wiremock.junit.WireMockRule;
-import java.io.IOException;
-import java.net.URL;
-import org.apache.logging.log4j.Level;
-import org.apache.logging.log4j.core.Appender;
-import org.apache.logging.log4j.core.config.Property;
-import org.apache.logging.log4j.core.impl.Log4jLogEvent;
-import org.apache.logging.log4j.core.lookup.JavaLookup;
-import org.apache.logging.log4j.core.net.ssl.KeyStoreConfiguration;
-import org.apache.logging.log4j.core.net.ssl.SslConfiguration;
-import org.apache.logging.log4j.core.net.ssl.TrustStoreConfiguration;
-import org.apache.logging.log4j.core.test.junit.LoggerContextRule;
-import org.apache.logging.log4j.core.test.net.ssl.TestConstants;
-import org.apache.logging.log4j.layout.template.json.JsonTemplateLayout;
-import org.apache.logging.log4j.message.SimpleMessage;
-import org.apache.logging.log4j.status.StatusData;
-import org.apache.logging.log4j.status.StatusListener;
-import org.apache.logging.log4j.status.StatusLogger;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
-
-@Ignore("Fails often on Windows")
-
-/* Fails often on Windows, for example:
-[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.20.1:test (default-test) on project log4j-core: There are test failures.
-[ERROR]
-[ERROR] Please refer to C:\vcs\git\apache\logging\logging-log4j2\log4j-core\target\surefire-reports for the individual test results.
-[ERROR] Please refer to dump files (if any exist) [date]-jvmRun[N].dump, [date].dumpstream and [date]-jvmRun[N].dumpstream.
-[ERROR] ExecutionException The forked VM terminated without properly saying goodbye. VM crash or System.exit called?
-[ERROR] Command was cmd.exe /X /C ""C:\Program Files\Java\jdk1.8.0_152\jre\bin\java" -Xms256m -Xmx1024m -jar C:\Users\ggregory\AppData\Local\Temp\surefire22320217597495112\surefirebooter1486874613063862199.jar C:\Users\ggregory\AppData\Local\Temp\surefire22320217597495112 2018-01-23T11-03-18_847-jvmRun6 surefire6375637980242546356tmp surefire_441335531705722358735tmp"
-[ERROR] Process Exit Code: 0
-[ERROR] Crashed tests:
-[ERROR] org.apache.logging.log4j.core.appender.HttpAppenderTest
-[ERROR] org.apache.maven.surefire.booter.SurefireBooterForkException: ExecutionException The forked VM terminated without properly saying goodbye. VM crash or System.exit called?
-[ERROR] Command was cmd.exe /X /C ""C:\Program Files\Java\jdk1.8.0_152\jre\bin\java" -Xms256m -Xmx1024m -jar C:\Users\ggregory\AppData\Local\Temp\surefire22320217597495112\surefirebooter1486874613063862199.jar C:\Users\ggregory\AppData\Local\Temp\surefire22320217597495112 2018-01-23T11-03-18_847-jvmRun6 surefire6375637980242546356tmp surefire_441335531705722358735tmp"
-[ERROR] Process Exit Code: 0
-[ERROR] Crashed tests:
-[ERROR] org.apache.logging.log4j.core.appender.HttpAppenderTest
-[ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.awaitResultsDone(ForkStarter.java:496)
-[ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.runSuitesForkPerTestSet(ForkStarter.java:443)
-[ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:295)
-[ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:246)
-[ERROR] at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:1124)
-[ERROR] at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:954)
-[ERROR] at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:832)
-[ERROR] at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
-[ERROR] at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
-[ERROR] at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
-[ERROR] at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
-[ERROR] at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
-[ERROR] at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
-[ERROR] at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
-[ERROR] at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
-[ERROR] at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:309)
-[ERROR] at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:194)
-[ERROR] at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:107)
-[ERROR] at org.apache.maven.cli.MavenCli.execute(MavenCli.java:955)
-[ERROR] at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:290)
-[ERROR] at org.apache.maven.cli.MavenCli.main(MavenCli.java:194)
-[ERROR] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
-[ERROR] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
-[ERROR] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
-[ERROR] at java.lang.reflect.Method.invoke(Method.java:498)
-[ERROR] at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
-[ERROR] at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
-[ERROR] at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
-[ERROR] at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
-[ERROR] Caused by: org.apache.maven.surefire.booter.SurefireBooterForkException: The forked VM terminated without properly saying goodbye. VM crash or System.exit called?
-[ERROR] Command was cmd.exe /X /C ""C:\Program Files\Java\jdk1.8.0_152\jre\bin\java" -Xms256m -Xmx1024m -jar C:\Users\ggregory\AppData\Local\Temp\surefire22320217597495112\surefirebooter1486874613063862199.jar C:\Users\ggregory\AppData\Local\Temp\surefire22320217597495112 2018-01-23T11-03-18_847-jvmRun6 surefire6375637980242546356tmp surefire_441335531705722358735tmp"
-[ERROR] Process Exit Code: 0
-[ERROR] Crashed tests:
-[ERROR] org.apache.logging.log4j.core.appender.HttpAppenderTest
-[ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:686)
-[ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:535)
-[ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.access$700(ForkStarter.java:116)
-[ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter$2.call(ForkStarter.java:431)
-[ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter$2.call(ForkStarter.java:408)
-[ERROR] at java.util.concurrent.FutureTask.run(FutureTask.java:266)
-[ERROR] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
-[ERROR] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
-[ERROR] at java.lang.Thread.run(Thread.java:748)
-[ERROR]
-[ERROR] -> [Help 1]
-[ERROR]
-[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
-[ERROR] Re-run Maven using the -X switch to enable full debug logging.
-[ERROR]
-[ERROR] For more information about the errors and possible solutions, please read the following articles:
-[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
-[ERROR]
-[ERROR] After correcting the problems, you can resume the build with the command
-[ERROR] mvn <goals> -rf :log4j-core
- */
-public class HttpAppenderTest {
-
- private static final String LOG_MESSAGE = "Hello, world!";
-
- private static Log4jLogEvent createLogEvent() {
- return Log4jLogEvent.newBuilder()
- .setLoggerName(HttpAppenderTest.class.getName())
- .setLoggerFqcn(HttpAppenderTest.class.getName())
- .setLevel(Level.INFO)
- .setMessage(new SimpleMessage(LOG_MESSAGE))
- .build();
- }
-
- private final ResponseDefinitionBuilder SUCCESS_RESPONSE = aResponse()
- .withStatus(201)
- .withHeader("Content-Type", "application/json")
- .withBody("{\"status\":\"created\"}");
-
- private final ResponseDefinitionBuilder FAILURE_RESPONSE = aResponse()
- .withStatus(400)
- .withHeader("Content-Type", "application/json")
- .withBody("{\"status\":\"error\"}");
-
- private final JavaLookup JAVA_LOOKUP = new JavaLookup();
-
- @Rule
- public LoggerContextRule ctx = new LoggerContextRule("HttpAppenderTest.xml");
-
- @Rule
- public WireMockRule wireMockRule = new WireMockRule(wireMockConfig()
- .dynamicPort()
- .dynamicHttpsPort()
- .keystorePath(TestConstants.KEYSTORE_FILE)
- .keystorePassword(String.valueOf(TestConstants.KEYSTORE_PWD()))
- .keyManagerPassword(String.valueOf(TestConstants.KEYSTORE_PWD()))
- .keystoreType(TestConstants.KEYSTORE_TYPE));
-
- private JsonTemplateLayout layout;
-
- @Before
- public void initLayout() {
- layout = JsonTemplateLayout.newBuilder()
- .setConfiguration(ctx.getConfiguration())
- .build();
- }
-
- @Test
- public void testAppend() throws Exception {
- wireMockRule.stubFor(post(urlEqualTo("/test/log4j/")).willReturn(SUCCESS_RESPONSE));
-
- final Appender appender = HttpAppender.newBuilder()
- .setName("Http")
- .setLayout(layout)
- .setConfiguration(ctx.getConfiguration())
- .setUrl(new URL("http://localhost:" + wireMockRule.port() + "/test/log4j/"))
- .build();
- appender.append(createLogEvent());
-
- wireMockRule.verify(postRequestedFor(urlEqualTo("/test/log4j/"))
- .withHeader("Host", containing("localhost"))
- .withHeader("Content-Type", containing("application/json"))
- .withRequestBody(containing("\"message\" : \"" + LOG_MESSAGE + "\"")));
- }
-
- @Test
- public void testAppendHttps() throws Exception {
- wireMockRule.stubFor(post(urlEqualTo("/test/log4j/")).willReturn(SUCCESS_RESPONSE));
-
- final Appender appender = HttpAppender.newBuilder()
- .setName("Http")
- .setLayout(layout)
- .setConfiguration(ctx.getConfiguration())
- .setUrl(new URL("https://localhost:" + wireMockRule.httpsPort() + "/test/log4j/"))
- .setSslConfiguration(SslConfiguration.createSSLConfiguration(
- null,
- KeyStoreConfiguration.createKeyStoreConfiguration(
- TestConstants.KEYSTORE_FILE,
- TestConstants.KEYSTORE_PWD(),
- null,
- null,
- TestConstants.KEYSTORE_TYPE,
- null),
- TrustStoreConfiguration.createKeyStoreConfiguration(
- TestConstants.TRUSTSTORE_FILE,
- TestConstants.TRUSTSTORE_PWD(),
- null,
- null,
- TestConstants.TRUSTSTORE_TYPE,
- null)))
- .setVerifyHostname(false)
- .build();
- appender.append(createLogEvent());
-
- wireMockRule.verify(postRequestedFor(urlEqualTo("/test/log4j/"))
- .withHeader("Host", containing("localhost"))
- .withHeader("Content-Type", containing("application/json"))
- .withRequestBody(containing("\"message\" : \"" + LOG_MESSAGE + "\"")));
- }
-
- @Test
- public void testAppendMethodPut() throws Exception {
- wireMockRule.stubFor(put(urlEqualTo("/test/log4j/1234")).willReturn(SUCCESS_RESPONSE));
-
- final Appender appender = HttpAppender.newBuilder()
- .setName("Http")
- .setLayout(layout)
- .setConfiguration(ctx.getConfiguration())
- .setMethod("PUT")
- .setUrl(new URL("http://localhost:" + wireMockRule.port() + "/test/log4j/1234"))
- .build();
- appender.append(createLogEvent());
-
- wireMockRule.verify(putRequestedFor(urlEqualTo("/test/log4j/1234"))
- .withHeader("Host", containing("localhost"))
- .withHeader("Content-Type", containing("application/json"))
- .withRequestBody(containing("\"message\" : \"" + LOG_MESSAGE + "\"")));
- }
-
- @Test
- public void testAppendCustomHeader() throws Exception {
- wireMockRule.stubFor(post(urlEqualTo("/test/log4j/")).willReturn(SUCCESS_RESPONSE));
-
- final Appender appender = HttpAppender.newBuilder()
- .setName("Http")
- .setLayout(layout)
- .setConfiguration(ctx.getConfiguration())
- .setUrl(new URL("http://localhost:" + wireMockRule.port() + "/test/log4j/"))
- .setHeaders(new Property[] {
- Property.createProperty("X-Test", "header value"),
- Property.createProperty("X-Runtime", "${java:runtime}")
- })
- .build();
- appender.append(createLogEvent());
-
- wireMockRule.verify(postRequestedFor(urlEqualTo("/test/log4j/"))
- .withHeader("Host", containing("localhost"))
- .withHeader("X-Test", equalTo("header value"))
- .withHeader("X-Runtime", equalTo(JAVA_LOOKUP.getRuntime()))
- .withHeader("Content-Type", containing("application/json"))
- .withRequestBody(containing("\"message\" : \"" + LOG_MESSAGE + "\"")));
- }
-
- volatile StatusData error;
-
- @Test
- public void testAppendErrorIgnore() throws Exception {
- wireMockRule.stubFor(post(urlEqualTo("/test/log4j/")).willReturn(FAILURE_RESPONSE));
-
- StatusLogger.getLogger().registerListener(new StatusListener() {
- @Override
- public void log(final StatusData data) {
- error = data;
- }
-
- @Override
- public Level getStatusLevel() {
- return Level.ERROR;
- }
-
- @Override
- public void close() throws IOException {}
- });
-
- error = null;
-
- final Appender appender = HttpAppender.newBuilder()
- .setName("Http")
- .setLayout(layout)
- .setConfiguration(ctx.getConfiguration())
- .setUrl(new URL("http://localhost:" + wireMockRule.port() + "/test/log4j/"))
- .build();
- appender.append(createLogEvent());
-
- wireMockRule.verify(postRequestedFor(urlEqualTo("/test/log4j/"))
- .withHeader("Host", containing("localhost"))
- .withHeader("Content-Type", containing("application/json"))
- .withRequestBody(containing("\"message\" : \"" + LOG_MESSAGE + "\"")));
-
- assertNotNull(error);
- assertEquals(Level.ERROR, error.getLevel());
- assertEquals(
- "Unable to send HTTP in appender [Http]", error.getMessage().toString());
- }
-
- @Test(expected = AppenderLoggingException.class)
- public void testAppendError() throws Exception {
- wireMockRule.stubFor(post(urlEqualTo("/test/log4j/")).willReturn(FAILURE_RESPONSE));
-
- final Appender appender = HttpAppender.newBuilder()
- .setName("Http")
- .setLayout(layout)
- .setConfiguration(ctx.getConfiguration())
- .setIgnoreExceptions(false)
- .setUrl(new URL("http://localhost:" + wireMockRule.port() + "/test/log4j/"))
- .build();
- appender.append(createLogEvent());
- }
-
- @Test(expected = AppenderLoggingException.class)
- public void testAppendConnectError() throws Exception {
- final Appender appender = HttpAppender.newBuilder()
- .setName("Http")
- .setLayout(layout)
- .setConfiguration(ctx.getConfiguration())
- .setIgnoreExceptions(false)
- .setUrl(new URL("http://localhost:" + (wireMockRule.port() + 1) + "/test/log4j/"))
- .build();
- appender.append(createLogEvent());
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/appender/SecureSocketAppenderSocketOptionsTest.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/appender/SecureSocketAppenderSocketOptionsTest.java
deleted file mode 100644
index 5623ac86f2..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/appender/SecureSocketAppenderSocketOptionsTest.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.appender;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.net.Socket;
-import javax.net.ssl.SSLServerSocketFactory;
-import org.apache.logging.log4j.core.appender.SocketAppenderTest.TcpSocketTestServer;
-import org.apache.logging.log4j.core.net.Rfc1349TrafficClass;
-import org.apache.logging.log4j.core.net.SocketOptions;
-import org.apache.logging.log4j.core.net.TcpSocketManager;
-import org.apache.logging.log4j.core.net.ssl.KeyStoreConfiguration;
-import org.apache.logging.log4j.core.net.ssl.SslConfiguration;
-import org.apache.logging.log4j.core.net.ssl.StoreConfigurationException;
-import org.apache.logging.log4j.core.net.ssl.TrustStoreConfiguration;
-import org.apache.logging.log4j.core.test.AvailablePortFinder;
-import org.apache.logging.log4j.core.test.junit.LoggerContextRule;
-import org.apache.logging.log4j.core.test.net.ssl.TestConstants;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.Assume;
-import org.junit.ClassRule;
-import org.junit.Test;
-
-public class SecureSocketAppenderSocketOptionsTest {
-
- private static final int PORT;
- private static TcpSocketTestServer tcpSocketTestServer;
-
- private static SSLServerSocketFactory serverSocketFactory;
- private static SslConfiguration sslConfiguration;
-
- static {
- PORT = AvailablePortFinder.getNextAvailable();
- System.setProperty("SecureSocketAppenderSocketOptionsTest.port", Integer.toString(PORT));
- try {
- initServerSocketFactory();
- tcpSocketTestServer = new TcpSocketTestServer(serverSocketFactory.createServerSocket(PORT));
- tcpSocketTestServer.start();
- loggerContextRule = new LoggerContextRule("log4j-ssl-socket-options.xml");
- } catch (IOException | StoreConfigurationException e) {
- throw new IllegalStateException(e);
- }
- }
-
- @ClassRule
- public static final LoggerContextRule loggerContextRule;
-
- @AfterClass
- public static void afterClass() {
- if (tcpSocketTestServer != null) {
- tcpSocketTestServer.shutdown();
- }
- }
-
- public static void initServerSocketFactory() throws StoreConfigurationException {
- final KeyStoreConfiguration ksc = KeyStoreConfiguration.createKeyStoreConfiguration(
- TestConstants.KEYSTORE_FILE, // file
- TestConstants.KEYSTORE_PWD(), // password
- null, // passwordEnvironmentVariable
- null, // passwordFile
- null, // key store type
- null); // algorithm
-
- final TrustStoreConfiguration tsc = TrustStoreConfiguration.createKeyStoreConfiguration(
- TestConstants.TRUSTSTORE_FILE, // file
- TestConstants.TRUSTSTORE_PWD(), // password
- null, // passwordEnvironmentVariable
- null, // passwordFile
- null, // key store type
- null); // algorithm
- sslConfiguration = SslConfiguration.createSSLConfiguration(null, ksc, tsc);
- serverSocketFactory = sslConfiguration.getSslServerSocketFactory();
- }
-
- @Test
- public void testSocketOptions() throws IOException {
- Assert.assertNotNull(loggerContextRule);
- Assert.assertNotNull(loggerContextRule.getConfiguration());
- final SocketAppender appender = loggerContextRule.getAppender("socket", SocketAppender.class);
- Assert.assertNotNull(appender);
- final TcpSocketManager manager = (TcpSocketManager) appender.getManager();
- Assert.assertNotNull(manager);
- final OutputStream outputStream = manager.getOutputStream();
- final OutputStream nullOutputStream = OutputStream.nullOutputStream();
- Assert.assertFalse(outputStream.getClass() == nullOutputStream.getClass());
- final SocketOptions socketOptions = manager.getSocketOptions();
- Assert.assertNotNull(socketOptions);
- final Socket socket = manager.getSocket();
- Assert.assertNotNull(socket);
- // Test config request
- Assert.assertEquals(false, socketOptions.isKeepAlive());
- Assert.assertEquals(null, socketOptions.isOobInline());
- Assert.assertEquals(false, socketOptions.isReuseAddress());
- Assert.assertEquals(false, socketOptions.isTcpNoDelay());
- Assert.assertEquals(
- Rfc1349TrafficClass.IPTOS_LOWCOST.value(),
- socketOptions.getActualTrafficClass().intValue());
- Assert.assertEquals(10000, socketOptions.getReceiveBufferSize().intValue());
- Assert.assertEquals(8000, socketOptions.getSendBufferSize().intValue());
- Assert.assertEquals(12345, socketOptions.getSoLinger().intValue());
- Assert.assertEquals(54321, socketOptions.getSoTimeout().intValue());
- // Test live socket
- Assert.assertEquals(false, socket.getKeepAlive());
- Assert.assertEquals(false, socket.getReuseAddress());
- Assert.assertEquals(false, socket.getTcpNoDelay());
- // Assert.assertEquals(10000, socket.getReceiveBufferSize());
- // This settings changes while we are running, so we cannot assert it.
- // Assert.assertEquals(8000, socket.getSendBufferSize());
- Assert.assertEquals(12345, socket.getSoLinger());
- Assert.assertEquals(54321, socket.getSoTimeout());
- }
-
- @Test
- public void testSocketTrafficClass() throws IOException {
- Assume.assumeTrue(
- "Run only on Java 7",
- System.getProperty("java.specification.version").equals("1.7"));
- Assume.assumeFalse("Do not run on Travis CI", "true".equals(System.getenv("TRAVIS")));
- final SocketAppender appender = loggerContextRule.getAppender("socket", SocketAppender.class);
- final TcpSocketManager manager = (TcpSocketManager) appender.getManager();
- final Socket socket = manager.getSocket();
- Assert.assertEquals(Rfc1349TrafficClass.IPTOS_LOWCOST.value(), socket.getTrafficClass());
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderBufferSizeTest.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderBufferSizeTest.java
deleted file mode 100644
index 0a61efa5c2..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderBufferSizeTest.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.appender;
-
-import org.apache.logging.log4j.ThreadContext;
-import org.apache.logging.log4j.core.Logger;
-import org.apache.logging.log4j.core.LoggerContext;
-import org.apache.logging.log4j.core.appender.SocketAppenderTest.TcpSocketTestServer;
-import org.apache.logging.log4j.core.test.AvailablePortFinder;
-import org.apache.logging.log4j.core.test.junit.LoggerContextRule;
-import org.apache.logging.log4j.core.util.Constants;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-
-/**
- *
- */
-public class SocketAppenderBufferSizeTest {
-
- private TcpSocketTestServer tcpServer;
-
- private LoggerContext loggerContext;
- private Logger logger;
-
- @Rule
- public LoggerContextRule loggerContextRule = new LoggerContextRule("log4j-empty.xml");
-
- @Before
- public void setup() throws Exception {
- tcpServer = new TcpSocketTestServer(AvailablePortFinder.getNextAvailable());
- tcpServer.start();
- ThreadContext.clearAll();
- loggerContext = loggerContextRule.getLoggerContext();
- logger = loggerContext.getLogger(SocketAppenderBufferSizeTest.class.getName());
- }
-
- @After
- public void teardown() {
- tcpServer.shutdown();
- loggerContext = null;
- logger = null;
- tcpServer.reset();
- ThreadContext.clearAll();
- }
-
- @Test
- public void testTcpAppenderDefaultEncoderBufferSize() throws Exception {
- SocketAppenderTest.testTcpAppender(tcpServer, logger, Constants.ENCODER_BYTE_BUFFER_SIZE);
- }
-
- @Test
- public void testTcpAppenderLargeEncoderBufferSize() throws Exception {
- SocketAppenderTest.testTcpAppender(tcpServer, logger, Constants.ENCODER_BYTE_BUFFER_SIZE * 100);
- }
-
- @Test
- public void testTcpAppenderSmallestEncoderBufferSize() throws Exception {
- SocketAppenderTest.testTcpAppender(tcpServer, logger, 1);
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderSocketOptionsTest.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderSocketOptionsTest.java
deleted file mode 100644
index 4a1e72a4d0..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderSocketOptionsTest.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.appender;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.net.Socket;
-import org.apache.logging.log4j.core.appender.SocketAppenderTest.TcpSocketTestServer;
-import org.apache.logging.log4j.core.net.AbstractSocketManager;
-import org.apache.logging.log4j.core.net.Rfc1349TrafficClass;
-import org.apache.logging.log4j.core.net.SocketOptions;
-import org.apache.logging.log4j.core.net.TcpSocketManager;
-import org.apache.logging.log4j.core.test.junit.AllocatePorts;
-import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
-import org.apache.logging.log4j.plugins.Named;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-@AllocatePorts("SocketAppenderSocketOptionsTest.port")
-public class SocketAppenderSocketOptionsTest {
-
- private TcpSocketTestServer server;
-
- @BeforeEach
- void setUp() throws IOException {
- final int port = Integer.getInteger("SocketAppenderSocketOptionsTest.port");
- server = new TcpSocketTestServer(port);
- server.start();
- }
-
- @AfterEach
- void tearDown() {
- if (server != null) {
- server.shutdown();
- server = null;
- }
- }
-
- @Test
- @LoggerContextSource("log4j-socket-options.xml")
- public void testSocketOptions(@Named("socket") final SocketAppender appender) throws IOException {
- final AbstractSocketManager abstractSocketManager = appender.getManager();
- assertThat(abstractSocketManager).isNotNull().isInstanceOf(TcpSocketManager.class);
- final TcpSocketManager manager = (TcpSocketManager) abstractSocketManager;
- final Class<? extends OutputStream> nullOutputStreamType =
- OutputStream.nullOutputStream().getClass();
- assertThat(manager.getOutputStream()).isNotNull().isInstanceOf(nullOutputStreamType);
- final SocketOptions socketOptions = manager.getSocketOptions();
- assertNotNull(socketOptions);
- final Socket socket = manager.getSocket();
- assertNotNull(socket);
- // Test config request
- assertEquals(false, socketOptions.isKeepAlive());
- assertEquals(false, socketOptions.isOobInline());
- assertEquals(false, socketOptions.isReuseAddress());
- assertEquals(false, socketOptions.isTcpNoDelay());
- assertEquals(
- Rfc1349TrafficClass.IPTOS_LOWCOST.value(),
- socketOptions.getActualTrafficClass().intValue());
- assertEquals(10000, socketOptions.getReceiveBufferSize().intValue());
- assertEquals(8000, socketOptions.getSendBufferSize().intValue());
- assertEquals(12345, socketOptions.getSoLinger().intValue());
- assertEquals(54321, socketOptions.getSoTimeout().intValue());
- // Test live socket
- assertFalse(socket.getKeepAlive());
- assertFalse(socket.getOOBInline());
- assertFalse(socket.getReuseAddress());
- assertFalse(socket.getTcpNoDelay());
- // Assert.assertEquals(10000, socket.getReceiveBufferSize());
- // This settings changes while we are running, so we cannot assert it.
- // Assert.assertEquals(8000, socket.getSendBufferSize());
- assertEquals(12345, socket.getSoLinger());
- assertEquals(54321, socket.getSoTimeout());
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderTest.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderTest.java
deleted file mode 100644
index f8a58a3fb6..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderTest.java
+++ /dev/null
@@ -1,447 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.appender;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.DatagramPacket;
-import java.net.DatagramSocket;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import java.util.concurrent.ArrayBlockingQueue;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-import org.apache.logging.log4j.Level;
-import org.apache.logging.log4j.LoggingException;
-import org.apache.logging.log4j.ThreadContext;
-import org.apache.logging.log4j.core.Appender;
-import org.apache.logging.log4j.core.Layout;
-import org.apache.logging.log4j.core.Logger;
-import org.apache.logging.log4j.core.LoggerContext;
-import org.apache.logging.log4j.core.config.DefaultConfiguration;
-import org.apache.logging.log4j.core.net.Protocol;
-import org.apache.logging.log4j.core.test.AvailablePortFinder;
-import org.apache.logging.log4j.core.util.Constants;
-import org.apache.logging.log4j.core.util.Throwables;
-import org.apache.logging.log4j.layout.template.json.JsonTemplateLayout;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Tag;
-import org.junit.jupiter.api.Test;
-
-/**
- *
- */
-@Tag("sleepy")
-public class SocketAppenderTest {
-
- private static final int PORT = AvailablePortFinder.getNextAvailable();
- private static final int DYN_PORT = AvailablePortFinder.getNextAvailable();
- private static final int ERROR_PORT = AvailablePortFinder.getNextAvailable();
-
- private static TcpSocketTestServer tcpServer;
- private static UdpSocketTestServer udpServer;
-
- private static final Layout LAYOUT = JsonTemplateLayout.newBuilder()
- .setConfiguration(new DefaultConfiguration())
- .setEventTemplate(LogEventDto.JSON_TEMPLATE)
- .build();
-
- public static final class LogEventDto {
-
- private static final String JSON_TEMPLATE = ("{" + "'message': {'$resolver': 'message', 'stringified': true},"
- + "'contextData': {'$resolver': 'mdc'},"
- + "'contextStack': {'$resolver': 'ndc'},"
- + "'error': {'$resolver': 'exception', 'field': 'message'}"
- + "}")
- .replaceAll("'", "\"");
-
- private static final ObjectMapper MAPPER = new ObjectMapper();
-
- private final String message;
-
- private final Map<String, String> contextData;
-
- private final List<String> contextStack;
-
- private final String error;
-
- @JsonCreator
- public LogEventDto(
- @JsonProperty("message") final String message,
- @JsonProperty("contextData") final Map<String, String> contextData,
- @JsonProperty("contextStack") final List<String> contextStack,
- @JsonProperty("error") final String error) {
- this.message = message;
- this.contextData = contextData;
- this.contextStack = contextStack;
- this.error = error;
- }
-
- private static LogEventDto fromJsonBytes(final byte[] jsonBytes) throws IOException {
- return MAPPER.readValue(jsonBytes, LogEventDto.class);
- }
-
- private static Iterator<LogEventDto> fromJsonByteStream(final InputStream stream) throws IOException {
- return MAPPER.readerFor(LogEventDto.class).readValues(stream);
- }
- }
-
- private final LoggerContext context = LoggerContext.getContext();
- private final Logger logger = context.getLogger(SocketAppenderTest.class.getName());
-
- @BeforeAll
- public static void setupClass() throws Exception {
- tcpServer = new TcpSocketTestServer(PORT);
- tcpServer.start();
- udpServer = new UdpSocketTestServer();
- udpServer.start();
- LoggerContext.getContext().reconfigure();
- ThreadContext.clearAll();
- }
-
- @AfterAll
- public static void cleanupClass() {
- tcpServer.shutdown();
- udpServer.shutdown();
- ThreadContext.clearAll();
- }
-
- @AfterEach
- public void teardown() {
- ThreadContext.clearAll();
- removeAndStopAppenders();
- reset();
- }
-
- void removeAndStopAppenders() {
- final Map<String, Appender> map = logger.getAppenders();
- for (final Map.Entry<String, Appender> entry : map.entrySet()) {
- final Appender appender = entry.getValue();
- logger.removeAppender(appender);
- appender.stop();
- }
- }
-
- static void reset() {
- tcpServer.reset();
- udpServer.reset();
- }
-
- @Test
- public void testTcpAppender1() throws Exception {
- testTcpAppender(tcpServer, logger, Constants.ENCODER_BYTE_BUFFER_SIZE);
- }
-
- @Test
- @Disabled("WIP Bug when this method runs after testTcpAppender1()")
- public void testTcpAppender2() throws Exception {
- testTcpAppender(tcpServer, logger, Constants.ENCODER_BYTE_BUFFER_SIZE);
- }
-
- static void testTcpAppender(final TcpSocketTestServer tcpTestServer, final Logger logger, final int bufferSize)
- throws Exception {
- // @formatter:off
- final SocketAppender appender = SocketAppender.newBuilder()
- .setHost("localhost")
- .setPort(tcpTestServer.getLocalPort())
- .setReconnectDelayMillis(-1)
- .setName("test")
- .setImmediateFail(false)
- .setBufferSize(bufferSize)
- .setLayout(LAYOUT)
- .build();
- // @formatter:on
- appender.start();
- assertEquals(bufferSize, appender.getManager().getByteBuffer().capacity());
-
- // set appender on root and set level to debug
- logger.addAppender(appender);
- logger.setAdditive(false);
- logger.setLevel(Level.DEBUG);
- final String tcKey = "UUID";
- final String expectedUuidStr = UUID.randomUUID().toString();
- ThreadContext.put(tcKey, expectedUuidStr);
- ThreadContext.push(expectedUuidStr);
- final String expectedExMsg = "This is a test";
- try {
- logger.debug("This is a test message");
- final Throwable child = new LoggingException(expectedExMsg);
- logger.error("Throwing an exception", child);
- logger.debug("This is another test message");
- } finally {
- ThreadContext.remove(tcKey);
- ThreadContext.pop();
- }
- Thread.sleep(250);
- LogEventDto event = tcpTestServer.getQueue().poll(3, TimeUnit.SECONDS);
- assertNotNull(event, "No event retrieved");
- assertEquals("This is a test message", event.message, "Incorrect event");
- assertTrue(tcpTestServer.getCount() > 0, "Message not delivered via TCP");
- assertEquals(expectedUuidStr, event.contextData.get(tcKey));
- event = tcpTestServer.getQueue().poll(3, TimeUnit.SECONDS);
- assertNotNull(event, "No event retrieved");
- assertEquals("Throwing an exception", event.message, "Incorrect event");
- assertTrue(tcpTestServer.getCount() > 1, "Message not delivered via TCP");
- assertThat(event.contextStack).containsOnly(expectedUuidStr);
- assertEquals(expectedExMsg, event.error);
- }
-
- @Test
- public void testDefaultProtocol() {
- // @formatter:off
- final SocketAppender appender = SocketAppender.newBuilder()
- .setPort(tcpServer.getLocalPort())
- .setReconnectDelayMillis(-1)
- .setName("test")
- .setImmediateFail(false)
- .setLayout(LAYOUT)
- .build();
- // @formatter:on
- assertNotNull(appender);
- appender.stop();
- }
-
- @Test
- public void testUdpAppender() throws Exception {
- final boolean released = udpServer.latch.await(3, TimeUnit.SECONDS);
- assertTrue(released);
-
- // @formatter:off
- final SocketAppender appender = SocketAppender.newBuilder()
- .setProtocol(Protocol.UDP)
- .setPort(tcpServer.getLocalPort())
- .setReconnectDelayMillis(-1)
- .setName("test")
- .setImmediateFail(false)
- .setLayout(LAYOUT)
- .build();
- // @formatter:on
- appender.start();
-
- // set appender on root and set level to debug
- logger.addAppender(appender);
- logger.setAdditive(false);
- logger.setLevel(Level.DEBUG);
- logger.debug("This is a udp message");
- final LogEventDto event = udpServer.getQueue().poll(3, TimeUnit.SECONDS);
- assertNotNull(event, "No event retrieved");
- assertEquals("This is a udp message", event.message, "Incorrect event");
- assertTrue(udpServer.getCount() > 0, "Message not delivered via UDP");
- }
-
- @Test
- public void testTcpAppenderDeadlock() throws Exception {
-
- // @formatter:off
- final SocketAppender appender = SocketAppender.newBuilder()
- .setHost("localhost")
- .setPort(DYN_PORT)
- .setReconnectDelayMillis(100)
- .setName("test")
- .setImmediateFail(false)
- .setLayout(LAYOUT)
- .build();
- // @formatter:on
- appender.start();
- // set appender on root and set level to debug
- logger.addAppender(appender);
- logger.setAdditive(false);
- logger.setLevel(Level.DEBUG);
-
- final TcpSocketTestServer tcpSocketServer = new TcpSocketTestServer(DYN_PORT);
- try {
- tcpSocketServer.start();
-
- logger.debug("This message is written because a deadlock never.");
-
- final LogEventDto event = tcpSocketServer.getQueue().poll(3, TimeUnit.SECONDS);
- assertNotNull(event, "No event retrieved");
- } finally {
- tcpSocketServer.shutdown();
- }
- }
-
- @Test
- public void testTcpAppenderNoWait() {
- // @formatter:off
- final SocketAppender appender = SocketAppender.newBuilder()
- .setHost("localhost")
- .setPort(ERROR_PORT)
- .setReconnectDelayMillis(100)
- .setName("test")
- .setImmediateFail(false)
- .setIgnoreExceptions(false)
- .setLayout(LAYOUT)
- .build();
- // @formatter:on
- appender.start();
- // set appender on root and set level to debug
- logger.addAppender(appender);
- logger.setAdditive(false);
- logger.setLevel(Level.DEBUG);
-
- assertThrows(Exception.class, () -> logger.debug("This message is written because a deadlock never."));
- }
-
- public static class UdpSocketTestServer extends Thread {
-
- private final DatagramSocket sock;
- private boolean shutdown = false;
- private Thread thread;
- private final CountDownLatch latch = new CountDownLatch(1);
- private final AtomicInteger count = new AtomicInteger();
- private final BlockingQueue<LogEventDto> queue;
-
- public UdpSocketTestServer() throws IOException {
- this.sock = new DatagramSocket(PORT);
- this.queue = new ArrayBlockingQueue<>(10);
- }
-
- public void reset() {
- queue.clear();
- count.set(0);
- }
-
- public void shutdown() {
- this.shutdown = true;
- thread.interrupt();
- try {
- thread.join(100);
- } catch (InterruptedException ie) {
- System.out.println("Unable to stop server");
- }
- }
-
- @Override
- public void run() {
- this.thread = Thread.currentThread();
- final byte[] bytes = new byte[4096];
- final DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
- try {
- while (!shutdown) {
- latch.countDown();
- sock.receive(packet);
- count.incrementAndGet();
- final LogEventDto event = LogEventDto.fromJsonBytes(packet.getData());
- queue.add(event);
- }
- } catch (final Throwable e) {
- e.printStackTrace();
- if (!shutdown) {
- Throwables.rethrow(e);
- }
- }
- }
-
- public int getCount() {
- return count.get();
- }
-
- public BlockingQueue<LogEventDto> getQueue() {
- return queue;
- }
- }
-
- public static class TcpSocketTestServer extends Thread {
-
- private final ServerSocket serverSocket;
- private volatile boolean shutdown = false;
- private final AtomicInteger count = new AtomicInteger();
- private final BlockingQueue<LogEventDto> queue;
-
- @SuppressWarnings("resource")
- public TcpSocketTestServer(final int port) throws IOException {
- this(new ServerSocket(port));
- }
-
- public TcpSocketTestServer(final ServerSocket serverSocket) {
- this.serverSocket = serverSocket;
- this.queue = new ArrayBlockingQueue<>(10);
- }
-
- public int getLocalPort() {
- return serverSocket.getLocalPort();
- }
-
- public void reset() {
- queue.clear();
- count.set(0);
- }
-
- public void shutdown() {
- this.shutdown = true;
- interrupt();
- try {
- this.join(100);
- } catch (InterruptedException ie) {
- System.out.println("Unable to stop server");
- }
- }
-
- @Override
- public void run() {
- try {
- try (final Socket socket = serverSocket.accept()) {
- if (socket != null) {
- final InputStream is = socket.getInputStream();
- while (!shutdown) {
- final Iterator<LogEventDto> it = LogEventDto.fromJsonByteStream(is);
- while (it.hasNext()) {
- final LogEventDto logEvent = it.next();
- queue.add(logEvent);
- count.incrementAndGet();
- }
- }
- }
- }
- } catch (final EOFException eof) {
- // Socket is closed.
- } catch (final Exception e) {
- if (!shutdown) {
- Throwables.rethrow(e);
- }
- }
- }
-
- public BlockingQueue<LogEventDto> getQueue() {
- return queue;
- }
-
- public int getCount() {
- return count.get();
- }
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/AbstractRunQueue.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/AbstractRunQueue.java
deleted file mode 100644
index fbf567bb4d..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/AbstractRunQueue.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-import java.util.Objects;
-import java.util.concurrent.BlockingQueue;
-import org.apache.logging.log4j.core.async.perftest.ResponseTimeTest.PrintingAsyncQueueFullPolicy;
-
-public abstract class AbstractRunQueue implements IPerfTestRunner {
-
- abstract BlockingQueue<String> createQueue(int capacity);
-
- private static final String STOP = "STOP_TEST";
- private volatile boolean stopped = false;
- private final BlockingQueue<String> queue = createQueue(256 * 1024);
- private final Thread backGroundThread;
-
- AbstractRunQueue() {
- backGroundThread = new Thread(() -> {
- for (; ; ) {
- try {
- if (Objects.equals(queue.take(), STOP)) {
- break;
- }
- } catch (final InterruptedException e) {
- e.printStackTrace();
- break;
- }
- }
- });
- backGroundThread.start();
- }
-
- @Override
- public void runThroughputTest(final int lines, final Histogram histogram) {}
-
- @Override
- public void runLatencyTest(
- final int samples, final Histogram histogram, final long nanoTimeCost, final int threadCount) {}
-
- @Override
- public final void shutdown() {
- stopped = true;
- try {
- queue.put(STOP);
- } catch (final InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public final void log(final String finalMessage) {
- if (stopped) {
- return;
- }
- if (!queue.offer(finalMessage)) {
- PrintingAsyncQueueFullPolicy.ringbufferFull.incrementAndGet();
- try {
- queue.put(finalMessage);
- } catch (final InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/Histogram.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/Histogram.java
deleted file mode 100644
index 49e6c8e729..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/Histogram.java
+++ /dev/null
@@ -1,344 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-import java.math.BigDecimal;
-import java.math.RoundingMode;
-import java.util.Arrays;
-
-/**
- * <p>Histogram for tracking the frequency of observations of values below interval upper bounds.</p>
- *
- * <p>This class is useful for recording timings across a large number of observations
- * when high performance is required.</p>
- *
- * <p>The interval bounds are used to define the ranges of the histogram buckets. If provided bounds
- * are [10,20,30,40,50] then there will be five buckets, accessible by index 0-4. Any value
- * 0-10 will fall into the first interval bar, values 11-20 will fall into the
- * second bar, and so on.</p>
- */
-@Deprecated
-public final class Histogram {
- // tracks the upper intervals of each of the buckets/bars
- private final long[] upperBounds;
- // tracks the count of the corresponding bucket
- private final long[] counts;
- // minimum value so far observed
- private long minValue = Long.MAX_VALUE;
- // maximum value so far observed
- private long maxValue = 0L;
-
- /**
- * Create a new Histogram with a provided list of interval bounds.
- *
- * @param upperBounds of the intervals. Bounds must be provided in order least to greatest, and
- * lowest bound must be greater than or equal to 1.
- * @throws IllegalArgumentException if any of the upper bounds are less than or equal to zero
- * @throws IllegalArgumentException if the bounds are not in order, least to greatest
- */
- public Histogram(final long[] upperBounds) {
- validateBounds(upperBounds);
-
- this.upperBounds = Arrays.copyOf(upperBounds, upperBounds.length);
- this.counts = new long[upperBounds.length];
- }
-
- /**
- * Validates the input bounds; used by constructor only.
- */
- private void validateBounds(final long[] upperBounds) {
- long lastBound = -1L;
- if (upperBounds.length <= 0) {
- throw new IllegalArgumentException("Must provide at least one interval");
- }
- for (final long bound : upperBounds) {
- if (bound <= 0L) {
- throw new IllegalArgumentException("Bounds must be positive values");
- }
-
- if (bound <= lastBound) {
- throw new IllegalArgumentException("bound " + bound + " is not greater than " + lastBound);
- }
-
- lastBound = bound;
- }
- }
-
- /**
- * Size of the list of interval bars (ie: count of interval bars).
- *
- * @return size of the interval bar list.
- */
- public int getSize() {
- return upperBounds.length;
- }
-
- /**
- * Get the upper bound of an interval for an index.
- *
- * @param index of the upper bound.
- * @return the interval upper bound for the index.
- */
- public long getUpperBoundAt(final int index) {
- return upperBounds[index];
- }
-
- /**
- * Get the count of observations at a given index.
- *
- * @param index of the observations counter.
- * @return the count of observations at a given index.
- */
- public long getCountAt(final int index) {
- return counts[index];
- }
-
- /**
- * Add an observation to the histogram and increment the counter for the interval it matches.
- *
- * @param value for the observation to be added.
- * @return return true if in the range of intervals and successfully added observation; otherwise false.
- */
- public boolean addObservation(final long value) {
- int low = 0;
- int high = upperBounds.length - 1;
-
- // do a classic binary search to find the high value
- while (low < high) {
- final int mid = low + ((high - low) >> 1);
- if (upperBounds[mid] < value) {
- low = mid + 1;
- } else {
- high = mid;
- }
- }
-
- // if the binary search found an eligible bucket, increment
- if (value <= upperBounds[high]) {
- counts[high]++;
- trackRange(value);
-
- return true;
- }
-
- // otherwise value was not found
- return false;
- }
-
- /**
- * Track minimum and maximum observations
- */
- private void trackRange(final long value) {
- if (value < minValue) {
- minValue = value;
- }
-
- if (value > maxValue) {
- maxValue = value;
- }
- }
-
- /**
- * <p>Add observations from another Histogram into this one.</p>
- *
- * <p>Histograms must have the same intervals.</p>
- *
- * @param histogram from which to add the observation counts.
- * @throws IllegalArgumentException if interval count or values do not match exactly
- */
- public void addObservations(final Histogram histogram) {
- // validate the intervals
- if (upperBounds.length != histogram.upperBounds.length) {
- throw new IllegalArgumentException("Histograms must have matching intervals");
- }
-
- for (int i = 0, size = upperBounds.length; i < size; i++) {
- if (upperBounds[i] != histogram.upperBounds[i]) {
- throw new IllegalArgumentException("Histograms must have matching intervals");
- }
- }
-
- // increment all of the internal counts
- for (int i = 0, size = counts.length; i < size; i++) {
- counts[i] += histogram.counts[i];
- }
-
- // refresh the minimum and maximum observation ranges
- trackRange(histogram.minValue);
- trackRange(histogram.maxValue);
- }
-
- /**
- * Clear the list of interval counters
- */
- public void clear() {
- maxValue = 0L;
- minValue = Long.MAX_VALUE;
-
- Arrays.fill(counts, 0L);
- }
-
- /**
- * Count total number of recorded observations.
- *
- * @return the total number of recorded observations.
- */
- public long getCount() {
- long count = 0L;
-
- for (int i = 0, size = counts.length; i < size; i++) {
- count += counts[i];
- }
-
- return count;
- }
-
- /**
- * Get the minimum observed value.
- *
- * @return the minimum value observed.
- */
- public long getMin() {
- return minValue;
- }
-
- /**
- * Get the maximum observed value.
- *
- * @return the maximum of the observed values;
- */
- public long getMax() {
- return maxValue;
- }
-
- /**
- * <p>Calculate the mean of all recorded observations.</p>
- *
- * <p>The mean is calculated by summing the mid points of each interval multiplied by the count
- * for that interval, then dividing by the total count of observations. The max and min are
- * considered for adjusting the top and bottom bin when calculating the mid point, this
- * minimises skew if the observed values are very far away from the possible histogram values.</p>
- *
- * @return the mean of all recorded observations.
- */
- public BigDecimal getMean() {
- // early exit to avoid divide by zero later
- if (0L == getCount()) {
- return BigDecimal.ZERO;
- }
-
- // precalculate the initial lower bound; needed in the loop
- long lowerBound = counts[0] > 0L ? minValue : 0L;
- // use BigDecimal to avoid precision errors
- BigDecimal total = BigDecimal.ZERO;
-
- // midpoint is calculated as the average between the lower and upper bound
- // (after taking into account the min & max values seen)
- // then, simply multiply midpoint by the count of values at the interval (intervalTotal)
- // and add to running total (total)
- for (int i = 0, size = upperBounds.length; i < size; i++) {
- if (0L != counts[i]) {
- final long upperBound = Math.min(upperBounds[i], maxValue);
- final long midPoint = lowerBound + ((upperBound - lowerBound) / 2L);
-
- final BigDecimal intervalTotal = new BigDecimal(midPoint).multiply(new BigDecimal(counts[i]));
- total = total.add(intervalTotal);
- }
-
- // and recalculate the lower bound for the next time around the loop
- lowerBound = Math.max(upperBounds[i] + 1L, minValue);
- }
-
- return total.divide(new BigDecimal(getCount()), 2, RoundingMode.HALF_UP);
- }
-
- /**
- * Calculate the upper bound within which 99% of observations fall.
- *
- * @return the upper bound for 99% of observations.
- */
- public long getTwoNinesUpperBound() {
- return getUpperBoundForFactor(0.99d);
- }
-
- /**
- * Calculate the upper bound within which 99.99% of observations fall.
- *
- * @return the upper bound for 99.99% of observations.
- */
- public long getFourNinesUpperBound() {
- return getUpperBoundForFactor(0.9999d);
- }
-
- /**
- * <p>Get the interval upper bound for a given factor of the observation population.</p>
- *
- * <p>Note this does not get the actual percentile measurement, it only gets the bucket</p>
- *
- * @param factor representing the size of the population.
- * @return the interval upper bound.
- * @throws IllegalArgumentException if factor < 0.0 or factor > 1.0
- */
- public long getUpperBoundForFactor(final double factor) {
- if (0.0d >= factor || factor >= 1.0d) {
- throw new IllegalArgumentException("factor must be >= 0.0 and <= 1.0");
- }
-
- final long totalCount = getCount();
- final long tailTotal = totalCount - Math.round(totalCount * factor);
- long tailCount = 0L;
-
- // reverse search the intervals ('tailCount' from end)
- for (int i = counts.length - 1; i >= 0; i--) {
- if (0L != counts[i]) {
- tailCount += counts[i];
- if (tailCount >= tailTotal) {
- return upperBounds[i];
- }
- }
- }
-
- return 0L;
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder();
-
- sb.append("Histogram{");
-
- sb.append("min=").append(getMin()).append(", ");
- sb.append("max=").append(getMax()).append(", ");
- sb.append("mean=").append(getMean()).append(", ");
- sb.append("99%=").append(getTwoNinesUpperBound()).append(", ");
- sb.append("99.99%=").append(getFourNinesUpperBound()).append(", ");
-
- sb.append('[');
- for (int i = 0, size = counts.length; i < size; i++) {
- sb.append(upperBounds[i]).append('=').append(counts[i]).append(", ");
- }
-
- if (counts.length > 0) {
- sb.setLength(sb.length() - 2);
- }
- sb.append(']');
-
- sb.append('}');
-
- return sb.toString();
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/IPerfTestRunner.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/IPerfTestRunner.java
deleted file mode 100644
index 977b191b95..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/IPerfTestRunner.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-public interface IPerfTestRunner {
- String LINE100 =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!\"#$%&'()-=^~|\\@`[]{};:+*,.<>/?_123456";
- String THROUGHPUT_MSG = LINE100 + LINE100 + LINE100 + LINE100 + LINE100;
- String LATENCY_MSG = "Short msg";
-
- void runThroughputTest(int lines, Histogram histogram);
-
- void runLatencyTest(int samples, Histogram histogram, long nanoTimeCost, int threadCount);
-
- void shutdown();
-
- void log(String finalMessage);
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/IdleStrategy.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/IdleStrategy.java
deleted file mode 100644
index 6b46eba880..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/IdleStrategy.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-/**
- * Idle strategy for use by threads when they do not have work to do.
- *
- * <h3>Note regarding potential for TTSP(Time To Safe Point) issues</h3>
- *
- * If the caller spins in a 'counted' loop, and the implementation does not include a a safepoint poll this may cause a TTSP
- * (Time To SafePoint) problem. If this is the case for your application you can solve it by preventing the idle method from
- * being inlined by using a Hotspot compiler command as a JVM argument e.g:
- * <code>-XX:CompileCommand=dontinline,org.apache.logging.log4j.core.async.perftest.NoOpIdleStrategy::idle</code>
- *
- * @see <a href="https://github.com/real-logic/Agrona/blob/master/src/main/java/org/agrona/concurrent/IdleStrategy.java">
- * https://github.com/real-logic/Agrona/blob/master/src/main/java/org/agrona/concurrent/IdleStrategy.java</a>
- */
-interface IdleStrategy {
- /**
- * Perform current idle action (e.g. nothing/yield/sleep).
- */
- void idle();
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/MultiThreadPerfTest.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/MultiThreadPerfTest.java
deleted file mode 100644
index 38ee47d0fd..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/MultiThreadPerfTest.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-import java.io.File;
-import java.util.concurrent.TimeUnit;
-
-public class MultiThreadPerfTest extends PerfTest {
-
- public static void main(final String[] args) throws Exception {
- new MultiThreadPerfTest().doMain(args);
- }
-
- @Override
- public void runTestAndPrintResult(
- final IPerfTestRunner runner, final String name, final int threadCount, final String resultFile)
- throws Exception {
-
- // ThreadContext.put("aKey", "mdcVal");
- PerfTest.println("Warming up the JVM...");
- final long t1 = System.nanoTime();
-
- // warmup at least 2 rounds and at most 1 minute
- final Histogram warmupHist = PerfTest.createHistogram();
- final long stop = System.nanoTime() + TimeUnit.MINUTES.toNanos(1);
- final Runnable run1 = () -> {
- for (int i = 0; i < 10; i++) {
- final int LINES = PerfTest.throughput ? 50000 : 200000;
- runTest(runner, LINES, null, warmupHist, 2);
- if (i > 0 && System.nanoTime() - stop >= 0) {
- return;
- }
- }
- };
- final Thread thread1 = new Thread(run1);
- final Thread thread2 = new Thread(run1);
- thread1.start();
- thread2.start();
- thread1.join();
- thread2.join();
-
- PerfTest.printf("Warmup complete in %.1f seconds%n", (System.nanoTime() - t1) / (1000.0 * 1000.0 * 1000.0));
- PerfTest.println("Waiting 10 seconds for buffers to drain warmup data...");
- Thread.sleep(10000);
- new File("perftest.log").delete();
- new File("perftest.log").createNewFile();
-
- PerfTest.println("Starting the main test...");
- PerfTest.throughput = false;
- multiThreadedTestRun(runner, name, threadCount, resultFile);
-
- Thread.sleep(1000);
- PerfTest.throughput = true;
- multiThreadedTestRun(runner, name, threadCount, resultFile);
- }
-
- private void multiThreadedTestRun(
- final IPerfTestRunner runner, final String name, final int threadCount, final String resultFile)
- throws Exception {
-
- final Histogram[] histograms = new Histogram[threadCount];
- for (int i = 0; i < histograms.length; i++) {
- histograms[i] = PerfTest.createHistogram();
- }
- final int LINES = 256 * 1024;
-
- final Thread[] threads = new Thread[threadCount];
- for (int i = 0; i < threads.length; i++) {
- final Histogram histogram = histograms[i];
- threads[i] = new Thread() {
- @Override
- public void run() {
- // int latencyCount = threadCount >= 16 ? 1000000 : 5000000;
- final int latencyCount = 5000000;
- final int count = PerfTest.throughput ? LINES / threadCount : latencyCount;
- runTest(runner, count, "end", histogram, threadCount);
- }
- };
- }
- for (final Thread thread : threads) {
- thread.start();
- }
- for (final Thread thread : threads) {
- thread.join();
- }
-
- for (final Histogram histogram : histograms) {
- PerfTest.reportResult(resultFile, name, histogram);
- }
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/NoOpIdleStrategy.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/NoOpIdleStrategy.java
deleted file mode 100644
index bc405d9e67..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/NoOpIdleStrategy.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-/**
- * No operation idle strategy.
- * <p>
- * This idle strategy should be prevented from being inlined by using a Hotspot compiler command as a JVM argument e.g:
- * <code>-XX:CompileCommand=dontinline,org.apache.logging.log4j.core.async.perftest.NoOpIdleStrategy::idle</code>
- * </p>
- */
-class NoOpIdleStrategy implements IdleStrategy {
-
- /**
- * <b>Note</b>: this implementation will result in no safepoint poll once inlined.
- *
- * @see IdleStrategy
- */
- @Override
- public void idle() {}
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/PerfTest.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/PerfTest.java
deleted file mode 100644
index 7bfb06c38e..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/PerfTest.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-import java.io.FileWriter;
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.util.Arrays;
-import java.util.concurrent.TimeUnit;
-import org.apache.logging.log4j.core.util.Loader;
-
-/**
- * Single-threaded performance test. Usually invoked from PerfTestDriver as part of a series of tests.
- * <p>
- * To run a single instance of this class for the log4j2 test runner:<br>
- * java -Dlog4j.configurationFile=mylog4j2.xml org.apache.logging.log4j.core.async.perftest.PerfTest \
- * org.apache.logging.log4j.core.async.perftest.RunLog4j2 <name> <resultfile.txt> <-verbose> <-throughput>
- */
-public class PerfTest {
-
- private static final String LINE100 =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!\"#$%&'()-=^~|\\@`[]{};:+*,.<>/?_123456";
- public static final String LINE500 = LINE100 + LINE100 + LINE100 + LINE100 + LINE100;
-
- static boolean verbose = false;
- static boolean throughput;
-
- // determine how long it takes to call System.nanoTime() (on average)
- static long calcNanoTimeCost() {
- final long iterations = 10000000;
- final long start = System.nanoTime();
- long finish = start;
-
- for (int i = 0; i < iterations; i++) {
- finish = System.nanoTime();
- }
-
- if (finish <= start) {
- throw new IllegalStateException();
- }
-
- finish = System.nanoTime();
- return (finish - start) / iterations;
- }
-
- static Histogram createHistogram() {
- final long[] intervals = new long[31];
- long intervalUpperBound = 1L;
- for (int i = 0, size = intervals.length - 1; i < size; i++) {
- intervalUpperBound *= 2;
- intervals[i] = intervalUpperBound;
- }
-
- intervals[intervals.length - 1] = Long.MAX_VALUE;
- return new Histogram(intervals);
- }
-
- public static void main(final String[] args) throws Exception {
- new PerfTest().doMain(args);
- }
-
- public void doMain(final String[] args) throws Exception {
- final String runnerClass = args[0];
- final IPerfTestRunner runner = Loader.newCheckedInstanceOf(runnerClass, IPerfTestRunner.class);
- final String name = args[1];
- final String resultFile = args.length > 2 ? args[2] : null;
- for (final String arg : args) {
- if (verbose && throughput) {
- break;
- }
- if ("-verbose".equalsIgnoreCase(arg)) {
- verbose = true;
- }
- if ("-throughput".equalsIgnoreCase(arg)) {
- throughput = true;
- }
- }
- final int threadCount = 1;
- printf("Starting %s %s (%d)...%n", getClass().getSimpleName(), name, threadCount);
- runTestAndPrintResult(runner, name, threadCount, resultFile);
- runner.shutdown();
- System.exit(0);
- }
-
- public void runTestAndPrintResult(
- final IPerfTestRunner runner, final String name, final int threadCount, final String resultFile)
- throws Exception {
- final Histogram warmupHist = createHistogram();
-
- // ThreadContext.put("aKey", "mdcVal");
- println("Warming up the JVM...");
- final long t1 = System.nanoTime();
-
- // warmup at least 10 seconds
- final int LINES = 50000;
- int iterations = 0;
- final long stop = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
- do {
- runTest(runner, LINES, null, warmupHist, 1);
- iterations++;
- } while (System.nanoTime() - stop < 0);
-
- printf(
- "Warmup complete in %.1f seconds (%d iterations)%n",
- (System.nanoTime() - t1) / (1000.0 * 1000.0 * 1000.0), iterations);
- println("Waiting 10 seconds for buffers to drain warmup data...");
-
- Thread.sleep(3000);
- // forceRemap(LINES, iterations, runner);
- Thread.sleep(7000);
-
- println("Starting the main test...");
- runSingleThreadedTest(runner, LINES, name, resultFile);
- Thread.sleep(1000);
- }
-
- /**
- * Log some extra bytes to fill the memory mapped buffer to force it to remap.
- */
- private void forceRemap(final int linesPerIteration, final int iterations, final IPerfTestRunner runner) {
- final int LINESEP = System.lineSeparator().getBytes(Charset.defaultCharset()).length;
- final int bytesPerLine = 0 + IPerfTestRunner.THROUGHPUT_MSG.getBytes().length;
- final int bytesWritten = bytesPerLine * linesPerIteration * iterations;
- final int threshold = 1073741824; // magic number: defined in perf9MMapLocation.xml
-
- int todo = threshold - bytesWritten;
- if (todo <= 0) {
- return;
- }
- final byte[] filler = new byte[4096];
- Arrays.fill(filler, (byte) 'X');
- final String str = new String(filler, Charset.defaultCharset());
- do {
- runner.log(str);
- } while ((todo -= (4096 + LINESEP)) > 0);
- }
-
- private int runSingleThreadedTest(
- final IPerfTestRunner runner, final int LINES, final String name, final String resultFile)
- throws IOException {
- final Histogram latency = createHistogram();
- runTest(runner, LINES, "end", latency, 1);
- reportResult(resultFile, name, latency);
- return LINES;
- }
-
- static void reportResult(final String file, final String name, final Histogram histogram) throws IOException {
- final String result = createSamplingReport(name, histogram);
- println(result);
-
- if (file != null) {
- try (final FileWriter writer = new FileWriter(file, true)) {
- writer.write(result);
- writer.write(System.lineSeparator());
- }
- }
- }
-
- static void printf(final String msg, final Object... objects) {
- if (verbose) {
- System.out.printf(msg, objects);
- }
- }
-
- static void println(final String msg) {
- if (verbose) {
- System.out.println(msg);
- }
- }
-
- static String createSamplingReport(final String name, final Histogram histogram) {
- final Histogram data = histogram;
- if (throughput) {
- return data.getMax() + " operations/second";
- }
- final String result = String.format(
- "avg=%.0f 99%%=%d 99.99%%=%d sampleCount=%d", //
- data.getMean(), //
- data.getTwoNinesUpperBound(), //
- data.getFourNinesUpperBound(), //
- data.getCount() //
- );
- return result;
- }
-
- public void runTest(
- final IPerfTestRunner runner,
- final int lines,
- final String finalMessage,
- final Histogram histogram,
- final int threadCount) {
- if (throughput) {
- runner.runThroughputTest(lines, histogram);
- } else {
- final long nanoTimeCost = calcNanoTimeCost();
- runner.runLatencyTest(lines, histogram, nanoTimeCost, threadCount);
- }
- if (finalMessage != null) {
- runner.log(finalMessage);
- }
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/PerfTestDriver.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/PerfTestDriver.java
deleted file mode 100644
index ea5b453cac..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/PerfTestDriver.java
+++ /dev/null
@@ -1,386 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.nio.CharBuffer;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import org.apache.logging.log4j.core.async.AsyncLoggerContextSelector;
-import org.apache.logging.log4j.core.util.Integers;
-
-/**
- * Runs a sequence of performance tests.
- */
-public class PerfTestDriver {
- private static final String DEFAULT_WAIT_STRATEGY = "Block";
-
- static enum WaitStrategy {
- Sleep,
- Yield,
- Block;
-
- public static WaitStrategy get() {
- return WaitStrategy.valueOf(System.getProperty("WaitStrategy", DEFAULT_WAIT_STRATEGY));
- }
- }
-
- /**
- * Defines the setup for a java process running a performance test.
- */
- static class Setup implements Comparable<Setup> {
- private final Class<?> klass;
- private final String log4jConfig;
- private final String name;
- private final String[] systemProperties;
- private final int threadCount;
- private final File temp;
- public Stats stats;
- private final WaitStrategy wait;
- private final Runner runner;
-
- public Setup(
- final Class<?> klass,
- final Runner runner,
- final String name,
- final String log4jConfig,
- final int threadCount,
- final WaitStrategy wait,
- final String... systemProperties)
- throws IOException {
- this.klass = klass;
- this.runner = runner;
- this.name = name;
- this.log4jConfig = log4jConfig;
- this.threadCount = threadCount;
- this.systemProperties = systemProperties;
- this.wait = wait;
- this.temp = File.createTempFile("log4jperformance", ".txt");
- }
-
- List<String> processArguments(final String java) {
- final List<String> args = new ArrayList<>();
- args.add(java);
- args.add("-server");
- args.add("-Xms1g");
- args.add("-Xmx1g");
-
- // args.add("-XX:+UseParallelOldGC");
- // args.add("-Xloggc:gc.log");
- // args.add("-XX:+PrintGCTimeStamps");
- // args.add("-XX:+PrintGCDetails");
- // args.add("-XX:+PrintGCDateStamps");
- // args.add("-XX:+PrintGCApplicationStoppedTime");
- // args.add("-XX:+PrintGCApplicationConcurrentTime");
- // args.add("-XX:+PrintSafepointStatistics");
-
- args.add("-Dlog4j.configuration=" + log4jConfig); // log4j 1.2
- args.add("-Dlog4j.configurationFile=" + log4jConfig); // log4j 2
- args.add("-Dlogback.configurationFile=" + log4jConfig); // logback
-
- final int ringBufferSize = getUserSpecifiedRingBufferSize();
- if (ringBufferSize >= 128) {
- args.add("-DAsyncLoggerConfig.RingBufferSize=" + ringBufferSize);
- args.add("-DAsyncLogger.RingBufferSize=" + ringBufferSize);
- }
- args.add("-DAsyncLoggerConfig.WaitStrategy=" + wait);
- args.add("-DAsyncLogger.WaitStrategy=" + wait);
- if (systemProperties != null) {
- Collections.addAll(args, systemProperties);
- }
- args.add("-cp");
- args.add(System.getProperty("java.class.path"));
- args.add(klass.getName());
- args.add(runner.implementationClass.getName());
- args.add(name);
- args.add(temp.getAbsolutePath());
- args.add(String.valueOf(threadCount));
- return args;
- }
-
- private int getUserSpecifiedRingBufferSize() {
- try {
- return Integers.parseInt(System.getProperty("RingBufferSize", "-1"));
- } catch (final Exception ignored) {
- return -1;
- }
- }
-
- ProcessBuilder latencyTest(final String java) {
- return new ProcessBuilder(processArguments(java));
- }
-
- ProcessBuilder throughputTest(final String java) {
- final List<String> args = processArguments(java);
- args.add("-throughput");
- return new ProcessBuilder(args);
- }
-
- @Override
- public int compareTo(final Setup other) {
- // largest ops/sec first
- return Long.signum(other.stats.averageOpsPerSec - stats.averageOpsPerSec);
- }
-
- public String description() {
- String detail = klass.getSimpleName();
- if (PerfTest.class == klass) {
- detail = "single thread";
- } else if (MultiThreadPerfTest.class == klass) {
- detail = threadCount + " threads";
- }
- final String target = runner.name();
- return target + ": " + name + " (" + detail + ')';
- }
- }
-
- /**
- * Results of a performance test.
- */
- static class Stats {
- int count;
- long average;
- long pct99;
- long pct99_99;
- double latencyRowCount;
- int throughputRowCount;
- private final long averageOpsPerSec; // Do not make final. Compile fails on Java 6.
-
- // example line: avg=828 99%=1118 99.99%=5028 Count=3125
- public Stats(final String raw) {
- final String[] lines = raw.split("[\\r\\n]+");
- long totalOps = 0;
- for (final String line : lines) {
- if (line.startsWith("avg")) {
- latencyRowCount++;
- final String[] parts = line.split(" ");
- int i = 0;
- average += Long.parseLong(parts[i++].split("=")[1]);
- pct99 += Long.parseLong(parts[i++].split("=")[1]);
- pct99_99 += Long.parseLong(parts[i++].split("=")[1]);
- count += Integers.parseInt(parts[i].split("=")[1]);
- } else {
- throughputRowCount++;
- final String number = line.substring(0, line.indexOf(' '));
- final long opsPerSec = Long.parseLong(number);
- totalOps += opsPerSec;
- }
- }
- averageOpsPerSec = totalOps / throughputRowCount;
- }
-
- @Override
- public String toString() {
- final String fmt = "throughput: %,d ops/sec. latency(ns): avg=%.1f 99%% < %.1f 99.99%% < %.1f (%d samples)";
- return String.format(
- fmt,
- averageOpsPerSec, //
- average / latencyRowCount, // mean latency
- pct99 / latencyRowCount, // 99% observations less than
- pct99_99 / latencyRowCount, // 99.99% observs less than
- count);
- }
- }
-
- static enum Runner {
- Log4j12(RunLog4j1.class), //
- Log4j2(RunLog4j2.class), //
- Logback(RunLogback.class);
-
- private final Class<? extends IPerfTestRunner> implementationClass;
-
- private Runner(final Class<? extends IPerfTestRunner> cls) {
- this.implementationClass = cls;
- }
- }
-
- public static void main(final String[] args) throws Exception {
- final long start = System.nanoTime();
-
- final List<Setup> tests = selectTests();
- runPerfTests(args, tests);
-
- System.out.printf(
- "Done. Total duration: %.1f minutes%n",
- (System.nanoTime() - start) / (60.0 * 1000.0 * 1000.0 * 1000.0));
-
- printRanking(tests.toArray(new Setup[tests.size()]));
- }
-
- private static List<Setup> selectTests() throws IOException {
- final List<Setup> tests = new ArrayList<>();
-
- // final String CACHEDCLOCK = "-Dlog4j.Clock=CachedClock";
- final String SYSCLOCK = "-Dlog4j.Clock=SystemClock";
- final String ALL_ASYNC = "-DLog4jContextSelector=" + AsyncLoggerContextSelector.class.getName();
-
- final String THREADNAME = "-DAsyncLogger.ThreadNameStrategy=" //
- + System.getProperty("AsyncLogger.ThreadNameStrategy", "CACHED");
-
- // includeLocation=false
- add(tests, 1, "perf3PlainNoLoc.xml", Runner.Log4j2, "Loggers all async", ALL_ASYNC, SYSCLOCK, THREADNAME);
- add(tests, 1, "perf7MixedNoLoc.xml", Runner.Log4j2, "Loggers mixed sync/async");
- add(tests, 1, "perf-logback.xml", Runner.Logback, "Sync");
- add(tests, 1, "perf-log4j12.xml", Runner.Log4j12, "Sync");
- add(tests, 1, "perf3PlainNoLoc.xml", Runner.Log4j2, "Sync");
- add(tests, 1, "perf-logback-async.xml", Runner.Logback, "Async Appender");
- add(tests, 1, "perf-log4j12-async.xml", Runner.Log4j12, "Async Appender");
- add(tests, 1, "perf5AsyncApndNoLoc.xml", Runner.Log4j2, "Async Appender");
-
- // includeLocation=true
- // add(tests, 1, "perf6AsyncApndLoc.xml", Runner.Log4j2, "Async Appender includeLocation");
- // add(tests, 1, "perf8MixedLoc.xml", Runner.Log4j2, "Mixed sync/async includeLocation");
- // add(tests, 1, "perf4PlainLocation.xml", Runner.Log4j2, "Loggers all async includeLocation", ALL_ASYNC);
- // add(tests, 1, "perf4PlainLocation.xml", Runner.Log4j2, "Loggers all async includeLocation CachedClock",
- // ALL_ASYNC, CACHEDCLOCK);
- // add(tests, 1, "perf4PlainLocation.xml", Runner.Log4j2, "Sync includeLocation");
-
- // appenders
- // add(tests, 1, "perf1syncFile.xml", Runner.Log4j2, "FileAppender");
- // add(tests, 1, "perf1syncRandomAccessFile.xml", Runner.Log4j2, "RandomAccessFileAppender");
- // add(tests, 1, "perf2syncRollFile.xml", Runner.Log4j2, "RollFileAppender");
- // add(tests, 1, "perf2syncRollRandomAccessFile.xml", Runner.Log4j2, "RollRandomAccessFileAppender");
-
- final int MAX_THREADS = 4; // 64 takes a LONG time
- for (int i = 2; i <= MAX_THREADS; i *= 2) {
- // includeLocation = false
- add(tests, i, "perf-logback.xml", Runner.Logback, "Sync");
- add(tests, i, "perf-log4j12.xml", Runner.Log4j12, "Sync");
- add(tests, i, "perf3PlainNoLoc.xml", Runner.Log4j2, "Sync");
- add(tests, i, "perf-logback-async.xml", Runner.Logback, "Async Appender");
- add(tests, i, "perf-log4j12-async.xml", Runner.Log4j12, "Async Appender");
- add(tests, i, "perf5AsyncApndNoLoc.xml", Runner.Log4j2, "Async Appender");
- add(tests, i, "perf3PlainNoLoc.xml", Runner.Log4j2, "Loggers all async", ALL_ASYNC, SYSCLOCK, THREADNAME);
- add(tests, i, "perf7MixedNoLoc.xml", Runner.Log4j2, "Loggers mixed sync/async");
-
- // includeLocation=true
- // add(tests, i, "perf6AsyncApndLoc.xml", Runner.Log4j2, "Async Appender includeLocation");
- // add(tests, i, "perf8MixedLoc.xml", Runner.Log4j2, "Mixed sync/async includeLocation");
- // add(tests, i, "perf4PlainLocation.xml", Runner.Log4j2, "Loggers all async includeLocation", ALL_ASYNC));
- // add(tests, i, "perf4PlainLocation.xml", Runner.Log4j2, "Loggers all async includeLocation CachedClock",
- // ALL_ASYNC, CACHEDCLOCK));
- // add(tests, i, "perf4PlainLocation.xml", Runner.Log4j2, "Sync includeLocation");
-
- // appenders
- // add(tests, i, "perf1syncFile.xml", Runner.Log4j2, "FileAppender");
- // add(tests, i, "perf1syncRandomAccessFile.xml", Runner.Log4j2, "RandomAccessFileAppender");
- // add(tests, i, "perf2syncRollFile.xml", Runner.Log4j2, "RollFileAppender");
- // add(tests, i, "perf2syncRollRandomAccessFile.xml", Runner.Log4j2, "RollRandomAccessFileAppender");
- }
- return tests;
- }
-
- private static void add(
- final List<Setup> tests,
- final int threadCount,
- final String config,
- final Runner runner,
- final String name,
- final String... systemProperties)
- throws IOException {
- final WaitStrategy wait = WaitStrategy.get();
- final Class<?> perfTest = threadCount == 1 ? PerfTest.class : MultiThreadPerfTest.class;
- final Setup setup = new Setup(perfTest, runner, name, config, threadCount, wait, systemProperties);
- tests.add(setup);
- }
-
- private static void runPerfTests(final String[] args, final List<Setup> tests)
- throws IOException, InterruptedException, FileNotFoundException {
- final String java = args.length > 0 ? args[0] : "java";
- final int repeat = args.length > 1 ? Integers.parseInt(args[1]) : 5;
- int x = 0;
- for (final Setup setup : tests) {
- System.out.print(setup.description());
- final ProcessBuilder pb = setup.throughputTest(java);
- pb.redirectErrorStream(true); // merge System.out and System.err
- final long t1 = System.nanoTime();
- final int count = setup.threadCount >= 4 ? 3 : repeat;
- runPerfTest(count, x++, setup, pb);
- System.out.printf(" took %.1f seconds%n", (System.nanoTime() - t1) / (1000.0 * 1000.0 * 1000.0));
-
- final FileReader reader = new FileReader(setup.temp);
- final CharBuffer buffer = CharBuffer.allocate(256 * 1024);
- reader.read(buffer);
- reader.close();
- setup.temp.delete();
- buffer.flip();
-
- final String raw = buffer.toString();
- System.out.print(raw);
- final Stats stats = new Stats(raw);
- System.out.println(stats);
- System.out.println("-----");
- setup.stats = stats;
- }
- new File("perftest.log").delete();
- }
-
- private static void printRanking(final Setup[] tests) {
- System.out.println();
- System.out.println("Ranking:");
- Arrays.sort(tests);
- for (int i = 0; i < tests.length; i++) {
- final Setup setup = tests[i];
- System.out.println((i + 1) + ". " + setup.description() + ": " + setup.stats);
- }
- }
-
- private static void runPerfTest(final int repeat, final int setupIndex, final Setup config, final ProcessBuilder pb)
- throws IOException, InterruptedException {
- for (int i = 0; i < repeat; i++) {
- System.out.print(" (" + (i + 1) + '/' + repeat + ")...");
- final Process process = pb.start();
-
- final boolean[] stop = {false};
- printProcessOutput(process, stop);
- process.waitFor();
- stop[0] = true;
-
- final File gc = new File("gc" + setupIndex + '_' + i + config.log4jConfig + ".log");
- if (gc.exists()) {
- gc.delete();
- }
- new File("gc.log").renameTo(gc);
- }
- }
-
- private static Thread printProcessOutput(final Process process, final boolean[] stop) {
-
- final Thread t = new Thread("OutputWriter") {
- @Override
- public void run() {
- final BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
- try {
- String line = null;
- while (!stop[0] && (line = in.readLine()) != null) {
- System.out.println(line);
- }
- } catch (final Exception ignored) {
- }
- }
- };
- t.start();
- return t;
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/PerfTestResultFormatter.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/PerfTestResultFormatter.java
deleted file mode 100644
index 35d6c07693..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/PerfTestResultFormatter.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.text.DecimalFormat;
-import java.text.NumberFormat;
-import java.text.ParseException;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-/**
- * Utility class that can read the "Ranking" output of the PerfTestDriver and
- * format it for pasting into Excel.
- */
-class PerfTestResultFormatter {
- static final String LF = System.lineSeparator();
- static final NumberFormat NUM = new DecimalFormat("#,##0");
-
- static class Stats {
- long throughput;
- double avgLatency;
- double latency99Pct;
- double latency99_99Pct;
-
- Stats(final String throughput, final String avg, final String lat99, final String lat99_99)
- throws ParseException {
- this.throughput = NUM.parse(throughput.trim()).longValue();
- this.avgLatency = Double.parseDouble(avg.trim());
- this.latency99Pct = Double.parseDouble(lat99.trim());
- this.latency99_99Pct = Double.parseDouble(lat99_99.trim());
- }
- }
-
- private final Map<String, Map<String, Stats>> results = new TreeMap<>();
-
- public PerfTestResultFormatter() {}
-
- public String format(final String text) throws ParseException {
- results.clear();
- final String[] lines = text.split("[\\r\\n]+");
- for (final String line : lines) {
- process(line);
- }
- return latencyTable() + LF + throughputTable();
- }
-
- private String latencyTable() {
- final StringBuilder sb = new StringBuilder(4 * 1024);
- final Set<String> subKeys = results.values().iterator().next().keySet();
- final char[] tabs = new char[subKeys.size()];
- Arrays.fill(tabs, '\t');
- final String sep = new String(tabs);
- sb.append("\tAverage latency")
- .append(sep)
- .append("99% less than")
- .append(sep)
- .append("99.99% less than");
- sb.append(LF);
- for (int i = 0; i < 3; i++) {
- for (final String subKey : subKeys) {
- sb.append('\t').append(subKey);
- }
- }
- sb.append(LF);
- for (final String key : results.keySet()) {
- sb.append(key);
- for (int i = 0; i < 3; i++) {
- final Map<String, Stats> sub = results.get(key);
- for (final String subKey : sub.keySet()) {
- final Stats stats = sub.get(subKey);
- switch (i) {
- case 0:
- sb.append('\t').append((long) stats.avgLatency);
- break;
- case 1:
- sb.append('\t').append((long) stats.latency99Pct);
- break;
- case 2:
- sb.append('\t').append((long) stats.latency99_99Pct);
- break;
- }
- }
- }
- sb.append(LF);
- }
- return sb.toString();
- }
-
- private String throughputTable() {
- final StringBuilder sb = new StringBuilder(4 * 1024);
- final Set<String> subKeys = results.values().iterator().next().keySet();
- sb.append("\tThroughput per thread (msg/sec)");
- sb.append(LF);
- for (final String subKey : subKeys) {
- sb.append('\t').append(subKey);
- }
- sb.append(LF);
- for (final String key : results.keySet()) {
- sb.append(key);
- final Map<String, Stats> sub = results.get(key);
- for (final String subKey : sub.keySet()) {
- final Stats stats = sub.get(subKey);
- sb.append('\t').append(stats.throughput);
- }
- sb.append(LF);
- }
- return sb.toString();
- }
-
- private void process(final String line) throws ParseException {
- final String key = line.substring(line.indexOf('.') + 1, line.indexOf('('));
- final String sub = line.substring(line.indexOf('(') + 1, line.indexOf(')'));
- final String throughput =
- line.substring(line.indexOf("throughput: ") + "throughput: ".length(), line.indexOf(" ops"));
- final String avg = line.substring(line.indexOf("avg=") + "avg=".length(), line.indexOf(" 99%"));
- final String pct99 = line.substring(line.indexOf("99% < ") + "99% < ".length(), line.indexOf(" 99.99%"));
- final String pct99_99 =
- line.substring(line.indexOf("99.99% < ") + "99.99% < ".length(), line.lastIndexOf('(') - 1);
- final Stats stats = new Stats(throughput, avg, pct99, pct99_99);
- Map<String, Stats> map = results.get(key.trim());
- if (map == null) {
- map = new TreeMap<>(sort());
- results.put(key.trim(), map);
- }
- String subKey = sub.trim();
- if ("single thread".equals(subKey)) {
- subKey = "1 thread";
- }
- map.put(subKey, stats);
- }
-
- private Comparator<String> sort() {
- return new Comparator<String>() {
- List<String> expected = Arrays.asList(
- "1 thread", "2 threads", "4 threads", "8 threads", "16 threads", "32 threads", "64 threads");
-
- @Override
- public int compare(final String o1, final String o2) {
- final int i1 = expected.indexOf(o1);
- final int i2 = expected.indexOf(o2);
- if (i1 < 0 || i2 < 0) {
- return o1.compareTo(o2);
- }
- return i1 - i2;
- }
- };
- }
-
- public static void main(final String[] args) throws Exception {
- final PerfTestResultFormatter fmt = new PerfTestResultFormatter();
- final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
- String line;
- while ((line = reader.readLine()) != null) {
- fmt.process(line);
- }
- System.out.println(fmt.latencyTable());
- System.out.println();
- System.out.println(fmt.throughputTable());
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/ResponseTimeTest.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/ResponseTimeTest.java
deleted file mode 100644
index f1c7d5e7d9..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/ResponseTimeTest.java
+++ /dev/null
@@ -1,410 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicLong;
-import org.HdrHistogram.Histogram;
-import org.apache.logging.log4j.Level;
-import org.apache.logging.log4j.core.async.DefaultAsyncQueueFullPolicy;
-import org.apache.logging.log4j.core.async.EventRoute;
-import org.apache.logging.log4j.core.util.Integers;
-import org.apache.logging.log4j.core.util.Loader;
-
-/**
- * Latency test showing both service time and response time.
- * <p>Service time = time to perform the desired operation, response time = service time + queueing time.</p>
- *
- * <h4>Gil's DOs and DONTs for latency testing</h4>
- * <p>
- * <a href="https://groups.google.com/d/msg/mechanical-sympathy/0gaBXxFm4hE/O9QomwHIJAAJ">https://groups.google.com/d/msg/mechanical-sympathy/0gaBXxFm4hE/O9QomwHIJAAJ</a>
- * </p>
- * If you are looking at the set of "stacks" below (all of which are queues/transports),
- * I would strongly encourage you to avoid repeating the mistakes of testing methodologies
- * that focus entirely on max achievable throughput and then report some (usually bogus)
- * latency stats at those max throughout modes.
- * The tech empower numbers are a classic example of this in play, and while they do provide some basis
- * for comparing a small aspect of behavior (what I call the "how fast can this thing drive off a cliff"
- * comparison, or "peddle to the metal" testing), those results are not very useful for comparing load
- * carrying capacities for anything that actually needs to maintain some form of responsiveness SLA or
- * latency spectrum requirements.
- * <p>
- * Rules of thumb I'd start with (some simple DOs and DON'Ts):
- * </p>
- * <ol>
- * <li>DO measure max achievable throughput, but DON'T get focused on it as the main or single axis of measurement /
- * comparison.
- * </li>
- * <li>DO measure response time / latency behaviors across a spectrum of attempted load levels (e.g. at attempted loads
- * between 2% to 100%+ of max established thoughout).</li>
- * <li>DO measure the response time / latency spectrum for each tested load (even for max throughout, for which response
- * time should linearly grow with test length, or the test is wrong). HdrHistogram is one good way to capture this
- * information.</li>
- * <li>DO make sure you are measuring response time correctly and labeling it right. If you also measure and report
- * service time, label it as such (don't call it "latency").</li>
- * <li>DO compare response time / latency spectrum at given loads.</li>
- * <li>DO [repeatedly] sanity check and calibrate the benchmark setup to verify that it produces expected results for
- * known forced scenarios. E.g. forced pauses of known size via ^Z or SIGSTOP/SIGCONT should produce expected response
- * time percentile levels. Attempting to load at >100% than achieved throughput should result in response time / latency
- * measurements that grow with benchmark run length, while service time (if measured) should remain fairly flat well
- * past saturation.</li>
- * <li>DON'T use or report standard deviation for latency. Ever. Except if you mean it as a joke.</li>
- * <li>DON'T use average latency as a way to compare things with one another. [use median or 90%'ile instead, if what
- * you want to compare is "common case" latencies]. Consider not reporting avg. at all.</li>
- * <li>DON'T compare results of different setups or loads from short runs (< 20-30 minutes).</li>
- * <li>DON'T include process warmup behavior (e.g. 1st minute and 1st 50K messages) in compared or reported
- * results.</li>
- * </ol>
- * <p.
- * See <a href="https://groups.google.com/d/msg/mechanical-sympathy/0gaBXxFm4hE/O9QomwHIJAAJ">https://groups.google.com/d/msg/mechanical-sympathy/0gaBXxFm4hE/O9QomwHIJAAJ</a>
- * for some concrete visual examples.
- */
-// RUN
-// java -XX:+UnlockDiagnosticVMOptions -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps
-// -XX:+PrintTenuringDistribution
-// -XX:+PrintGCApplicationConcurrentTime -XX:+PrintGCApplicationStoppedTime -XX:GuaranteedSafepointInterval=500000
-// -XX:CompileCommand=dontinline,org.apache.logging.log4j.core.async.perftest.NoOpIdleStrategy::idle
-// -cp
-// HdrHistogram-2.1.8.jar:disruptor-3.3.4.jar:log4j-api-2.6-SNAPSHOT.jar:log4j-core-2.6-SNAPSHOT.jar:log4j-core-2.6-SNAPSHOT-tests.jar
-// -DAsyncLogger.WaitStrategy=busyspin
-// -DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
-// -Dlog4j2.enable.threadlocals=true -Dlog4j2.enable.direct.encoders=true
-// -Xms1G -Xmx1G org.apache.logging.log4j.core.async.perftest.ResponseTimeTest 1 100000
-//
-// RUN recording in Java Flight Recorder:
-// %JAVA_HOME%\bin\java -XX:+UnlockCommercialFeatures -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints
-// -XX:+FlightRecorder -XX:StartFlightRecording=duration=10m,filename=replayStats-2.6-latency.jfr -verbose:gc
-// -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintTenuringDistribution -XX:+PrintGCApplicationConcurrentTime
-// -XX:+PrintGCApplicationStoppedTime
-// -XX:CompileCommand=dontinline,org.apache.logging.log4j.core.async.perftest.NoOpIdleStrategy::idle
-// -DAsyncLogger.WaitStrategy=yield -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=TRACE -cp
-// .;HdrHistogram-2.1.8.jar;disruptor-3.3.4.jar;log4j-api-2.6-SNAPSHOT.jar;log4j-core-2.6-SNAPSHOT.jar;log4j-core-2.6-SNAPSHOT-tests.jar org.apache.logging.log4j.core.async.perftest.ResponseTimeTest 1 50000
-public class ResponseTimeTest {
- private static final String LATENCY_MSG = new String(new char[64]);
-
- public static void main(final String[] args) throws Exception {
- if (args.length < 2) {
- System.out.println("Please specify thread count, target throughput (msg/sec) "
- + "and logger library (Log4j1, Log4j2, Logback, JUL)");
- return;
- }
- final int threadCount = Integers.parseInt(args[0]);
- final double loadMessagesPerSec = Double.parseDouble(args[1]);
- final String loggerLib = args.length > 2 ? args[2] : "Log4j2";
-
- // print to console if ringbuffer is full
- System.setProperty("log4j2.AsyncQueueFullPolicy", PrintingAsyncQueueFullPolicy.class.getName());
- System.setProperty("AsyncLogger.RingBufferSize", String.valueOf(256 * 1024));
- // System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getName());
- // System.setProperty("log4j.configurationFile", "perf3PlainNoLoc.xml");
- if (System.getProperty("AsyncLogger.WaitStrategy") == null) {
- System.setProperty("AsyncLogger.WaitStrategy", "Yield");
- }
- // for (Object key : System.getProperties().keySet()) {
- // System.out.println(key + "=" + System.getProperty((String) key));
- // }
-
- // initialize the logger
- final String wrapper = loggerLib.startsWith("Run") ? loggerLib : "Run" + loggerLib;
- final String loggerWrapperClass = "org.apache.logging.log4j.core.async.perftest." + wrapper;
- final IPerfTestRunner logger = Loader.newCheckedInstanceOf(loggerWrapperClass, IPerfTestRunner.class);
- logger.log("Starting..."); // ensure initialized
- Thread.sleep(100);
-
- final int requiredProcessors = threadCount + 1 + 1; // producers + 1 consumer + 1 for OS
- final IdleStrategy idleStrategy = Runtime.getRuntime().availableProcessors() > requiredProcessors
- ? new NoOpIdleStrategy()
- : new YieldIdleStrategy();
-
- System.out.printf(
- "%s: %d threads, load is %,f msg/sec, using %s%n",
- loggerLib,
- threadCount,
- loadMessagesPerSec,
- idleStrategy.getClass().getSimpleName());
-
- // Warmup: run as many iterations of 50,000 calls to logger.log as we can in 1 minute
- final long WARMUP_DURATION_MILLIS = TimeUnit.MINUTES.toMillis(1);
- final List<Histogram> warmupServiceTmHistograms = new ArrayList<>(threadCount);
- final List<Histogram> warmupResponseTmHistograms = new ArrayList<>(threadCount);
-
- final int WARMUP_COUNT = 50000 / threadCount;
- runLatencyTest(
- logger,
- WARMUP_DURATION_MILLIS,
- WARMUP_COUNT,
- loadMessagesPerSec,
- idleStrategy,
- warmupServiceTmHistograms,
- warmupResponseTmHistograms,
- threadCount);
- System.out.println("-----------------Warmup done. load=" + loadMessagesPerSec);
- System.out.println("-----------------Starting measured run. load=" + loadMessagesPerSec);
-
- final long start = System.currentTimeMillis();
- final List<Histogram> serviceTmHistograms = new ArrayList<>(threadCount);
- final List<Histogram> responseTmHistograms = new ArrayList<>(threadCount);
- PrintingAsyncQueueFullPolicy.ringbufferFull.set(0);
-
- // Actual test: run as many iterations of 1,000,000 calls to logger.log as we can in 4 minutes.
- final long TEST_DURATION_MILLIS = TimeUnit.MINUTES.toMillis(4);
- final int COUNT = (1000 * 1000) / threadCount;
- runLatencyTest(
- logger,
- TEST_DURATION_MILLIS,
- COUNT,
- loadMessagesPerSec,
- idleStrategy,
- serviceTmHistograms,
- responseTmHistograms,
- threadCount);
- logger.shutdown();
- final long end = System.currentTimeMillis();
-
- // ... and report the results
- final Histogram resultServiceTm = createResultHistogram(serviceTmHistograms, start, end);
- resultServiceTm.outputPercentileDistribution(System.out, 1000.0);
- writeToFile("s", resultServiceTm, (int) (loadMessagesPerSec / 1000), 1000.0);
-
- final Histogram resultResponseTm = createResultHistogram(responseTmHistograms, start, end);
- resultResponseTm.outputPercentileDistribution(System.out, 1000.0);
- writeToFile("r", resultResponseTm, (int) (loadMessagesPerSec / 1000), 1000.0);
-
- System.out.printf(
- "%n%s: %d threads, load %,f msg/sec, ringbuffer full=%d%n",
- loggerLib, threadCount, loadMessagesPerSec, PrintingAsyncQueueFullPolicy.ringbufferFull.get());
- System.out.println("Test duration: " + (end - start) / 1000.0 + " seconds");
- }
-
- private static void writeToFile(
- final String suffix, final Histogram hist, final int thousandMsgPerSec, final double scale)
- throws IOException {
- try (PrintStream pout = new PrintStream(new FileOutputStream(thousandMsgPerSec + "k" + suffix))) {
- hist.outputPercentileDistribution(pout, scale);
- }
- }
-
- private static Histogram createResultHistogram(final List<Histogram> list, final long start, final long end) {
- final Histogram result = new Histogram(TimeUnit.SECONDS.toNanos(10), 3);
- result.setStartTimeStamp(start);
- result.setEndTimeStamp(end);
- for (final Histogram hist : list) {
- result.add(hist);
- }
- return result;
- }
-
- public static void runLatencyTest(
- final IPerfTestRunner logger,
- final long durationMillis,
- final int samples,
- final double loadMessagesPerSec,
- final IdleStrategy idleStrategy,
- final List<Histogram> serviceTmHistograms,
- final List<Histogram> responseTmHistograms,
- final int threadCount)
- throws InterruptedException {
-
- final Thread[] threads = new Thread[threadCount];
- final CountDownLatch LATCH = new CountDownLatch(threadCount);
- for (int i = 0; i < threadCount; i++) {
- final Histogram serviceTmHist = new Histogram(TimeUnit.SECONDS.toNanos(10), 3);
- final Histogram responseTmHist = new Histogram(TimeUnit.SECONDS.toNanos(10), 3);
- serviceTmHistograms.add(serviceTmHist);
- responseTmHistograms.add(responseTmHist);
-
- threads[i] = new Thread("latencytest-" + i) {
- @Override
- public void run() {
- LATCH.countDown();
- try {
- LATCH.await(); // wait until all threads are ready to go
- } catch (final InterruptedException e) {
- interrupt();
- return;
- }
- final long endTimeMillis = System.currentTimeMillis() + durationMillis;
- do {
- final Pacer pacer = new Pacer(loadMessagesPerSec, idleStrategy);
- runLatencyTest(samples, logger, serviceTmHist, responseTmHist, pacer);
- } while (System.currentTimeMillis() < endTimeMillis);
- }
- };
- threads[i].start();
- }
- for (int i = 0; i < threadCount; i++) {
- threads[i].join();
- }
- }
-
- private static void runLatencyTest(
- final int samples,
- final IPerfTestRunner logger,
- final Histogram serviceTmHist,
- final Histogram responseTmHist,
- final Pacer pacer) {
-
- for (int i = 0; i < samples; i++) {
- final long expectedStartTimeNanos = pacer.expectedNextOperationNanoTime();
- pacer.acquire(1);
- final long actualStartTime = System.nanoTime();
- logger.log(LATENCY_MSG);
- final long doneTime = System.nanoTime();
- serviceTmHist.recordValue(doneTime - actualStartTime);
- responseTmHist.recordValue(doneTime - expectedStartTimeNanos);
- }
- }
-
- public static class PrintingAsyncQueueFullPolicy extends DefaultAsyncQueueFullPolicy {
- static AtomicLong ringbufferFull = new AtomicLong();
-
- @Override
- public EventRoute getRoute(final long backgroundThreadId, final Level level) {
- ringbufferFull.incrementAndGet();
- System.out.print('!');
- return super.getRoute(backgroundThreadId, level);
- }
- }
-
- /**
- * Pacer determines the pace at which measurements are taken. Sample usage:
- * <p/>
- * <pre>
- * - each thread has a Pacer instance
- * - at start of test, call pacer.setInitialStartTime(System.nanoTime());
- * - loop:
- * - store result of pacer.expectedNextOperationNanoTime() as expectedStartTime
- * - pacer.acquire(1);
- * - before the measured operation: store System.nanoTime() as actualStartTime
- * - perform the measured operation
- * - store System.nanoTime() as doneTime
- * - serviceTimeHistogram.recordValue(doneTime - actualStartTime);
- * - responseTimeHistogram.recordValue(doneTime - expectedStartTime);
- * </pre>
- * <p>
- * Borrowed with permission from Gil Tene's Cassandra stress test:
- * https://github.com/LatencyUtils/cassandra-stress2/blob/trunk/tools/stress/src/org/apache/cassandra/stress/StressAction.java#L374
- * </p>
- */
- static class Pacer {
- private long initialStartTime;
- private double throughputInUnitsPerNsec;
- private long unitsCompleted;
-
- private boolean caughtUp = true;
- private long catchUpStartTime;
- private long unitsCompletedAtCatchUpStart;
- private double catchUpThroughputInUnitsPerNsec;
- private double catchUpRateMultiple;
- private final IdleStrategy idleStrategy;
-
- public Pacer(final double unitsPerSec, final IdleStrategy idleStrategy) {
- this(unitsPerSec, 3.0, idleStrategy); // Default to catching up at 3x the set throughput
- }
-
- public Pacer(final double unitsPerSec, final double catchUpRateMultiple, final IdleStrategy idleStrategy) {
- this.idleStrategy = idleStrategy;
- setThroughout(unitsPerSec);
- setCatchupRateMultiple(catchUpRateMultiple);
- initialStartTime = System.nanoTime();
- }
-
- public void setInitialStartTime(final long initialStartTime) {
- this.initialStartTime = initialStartTime;
- }
-
- public void setThroughout(final double unitsPerSec) {
- throughputInUnitsPerNsec = unitsPerSec / 1000000000.0;
- catchUpThroughputInUnitsPerNsec = catchUpRateMultiple * throughputInUnitsPerNsec;
- }
-
- public void setCatchupRateMultiple(final double multiple) {
- catchUpRateMultiple = multiple;
- catchUpThroughputInUnitsPerNsec = catchUpRateMultiple * throughputInUnitsPerNsec;
- }
-
- /**
- * @return the time for the next operation
- */
- public long expectedNextOperationNanoTime() {
- return initialStartTime + (long) (unitsCompleted / throughputInUnitsPerNsec);
- }
-
- public long nsecToNextOperation() {
-
- final long now = System.nanoTime();
-
- long nextStartTime = expectedNextOperationNanoTime();
-
- boolean sendNow = true;
-
- if (nextStartTime > now) {
- // We are on pace. Indicate caught_up and don't send now.}
- caughtUp = true;
- sendNow = false;
- } else {
- // We are behind
- if (caughtUp) {
- // This is the first fall-behind since we were last caught up
- caughtUp = false;
- catchUpStartTime = now;
- unitsCompletedAtCatchUpStart = unitsCompleted;
- }
-
- // Figure out if it's time to send, per catch up throughput:
- final long unitsCompletedSinceCatchUpStart = unitsCompleted - unitsCompletedAtCatchUpStart;
-
- nextStartTime =
- catchUpStartTime + (long) (unitsCompletedSinceCatchUpStart / catchUpThroughputInUnitsPerNsec);
-
- if (nextStartTime > now) {
- // Not yet time to send, even at catch-up throughout:
- sendNow = false;
- }
- }
-
- return sendNow ? 0 : (nextStartTime - now);
- }
-
- /**
- * Will wait for next operation time. After this the expectedNextOperationNanoTime() will move forward.
- *
- * @param unitCount
- */
- public void acquire(final long unitCount) {
- final long nsecToNextOperation = nsecToNextOperation();
- if (nsecToNextOperation > 0) {
- sleepNs(nsecToNextOperation);
- }
- unitsCompleted += unitCount;
- }
-
- private void sleepNs(final long ns) {
- long now = System.nanoTime();
- final long deadline = now + ns;
- while ((now = System.nanoTime()) < deadline) {
- idleStrategy.idle();
- }
- }
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/RunConversant.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/RunConversant.java
deleted file mode 100644
index a5ce8bc87b..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/RunConversant.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-import com.conversantmedia.util.concurrent.SpinPolicy;
-import java.util.concurrent.BlockingQueue;
-import org.apache.logging.log4j.core.async.DisruptorBlockingQueueFactory;
-
-public class RunConversant extends AbstractRunQueue {
-
- @Override
- BlockingQueue<String> createQueue(final int capacity) {
- return DisruptorBlockingQueueFactory.<String>createFactory(SpinPolicy.SPINNING)
- .create(capacity);
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/RunJCTools.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/RunJCTools.java
deleted file mode 100644
index d84d86d86a..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/RunJCTools.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-import java.util.concurrent.BlockingQueue;
-import org.apache.logging.log4j.core.async.JCToolsBlockingQueueFactory;
-import org.apache.logging.log4j.core.async.JCToolsBlockingQueueFactory.WaitStrategy;
-
-public class RunJCTools extends AbstractRunQueue {
-
- @Override
- BlockingQueue<String> createQueue(final int capacity) {
- return JCToolsBlockingQueueFactory.<String>createFactory(WaitStrategy.SPIN)
- .create(capacity);
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/RunLog4j1.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/RunLog4j1.java
deleted file mode 100644
index db5a0987c0..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/RunLog4j1.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-import org.apache.log4j.LogManager;
-import org.apache.log4j.Logger;
-
-public class RunLog4j1 implements IPerfTestRunner {
-
- final Logger LOGGER = LogManager.getLogger(getClass());
-
- @Override
- public void runThroughputTest(final int lines, final Histogram histogram) {
- final long s1 = System.nanoTime();
- final Logger logger = LOGGER;
- for (int j = 0; j < lines; j++) {
- logger.info(THROUGHPUT_MSG);
- }
- final long s2 = System.nanoTime();
- final long opsPerSec = (1000L * 1000L * 1000L * lines) / (s2 - s1);
- histogram.addObservation(opsPerSec);
- }
-
- @Override
- public void runLatencyTest(
- final int samples, final Histogram histogram, final long nanoTimeCost, final int threadCount) {
- final Logger logger = LOGGER;
- for (int i = 0; i < samples; i++) {
- final long s1 = System.nanoTime();
- logger.info(LATENCY_MSG);
- final long s2 = System.nanoTime();
- final long value = s2 - s1 - nanoTimeCost;
- if (value > 0) {
- histogram.addObservation(value);
- }
- // wait 1 microsec
- final long PAUSE_NANOS = 10000 * threadCount;
- final long pauseStart = System.nanoTime();
- while (PAUSE_NANOS > (System.nanoTime() - pauseStart)) {
- // busy spin
- }
- }
- }
-
- @Override
- public void shutdown() {
- LogManager.shutdown();
- }
-
- @Override
- public void log(final String finalMessage) {
- LOGGER.info(finalMessage);
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/RunLog4j2.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/RunLog4j2.java
deleted file mode 100644
index cd0a0ac28a..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/RunLog4j2.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.core.CoreLoggerContexts;
-
-public class RunLog4j2 implements IPerfTestRunner {
- final Logger LOGGER = LogManager.getLogger(getClass());
-
- @Override
- public void runThroughputTest(final int lines, final Histogram histogram) {
- final long s1 = System.nanoTime();
- final Logger logger = LOGGER;
- for (int j = 0; j < lines; j++) {
- logger.info(THROUGHPUT_MSG);
- }
- final long s2 = System.nanoTime();
- final long opsPerSec = (1000L * 1000L * 1000L * lines) / (s2 - s1);
- histogram.addObservation(opsPerSec);
- }
-
- @Override
- public void runLatencyTest(
- final int samples, final Histogram histogram, final long nanoTimeCost, final int threadCount) {
- final Logger logger = LOGGER;
- for (int i = 0; i < samples; i++) {
- final long s1 = System.nanoTime();
- logger.info(LATENCY_MSG);
- final long s2 = System.nanoTime();
- final long value = s2 - s1 - nanoTimeCost;
- if (value > 0) {
- histogram.addObservation(value);
- }
- // wait 1 microsec
- final long PAUSE_NANOS = 10000 * threadCount;
- final long pauseStart = System.nanoTime();
- while (PAUSE_NANOS > (System.nanoTime() - pauseStart)) {
- // busy spin
- }
- }
- }
-
- @Override
- public void shutdown() {
- CoreLoggerContexts.stopLoggerContext(); // stop async thread
- }
-
- @Override
- public void log(final String finalMessage) {
- LOGGER.info(finalMessage);
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/RunLogback.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/RunLogback.java
deleted file mode 100644
index 9ab0c25cd1..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/RunLogback.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-import ch.qos.logback.classic.Logger;
-import ch.qos.logback.core.spi.LifeCycle;
-import org.slf4j.LoggerFactory;
-
-public class RunLogback implements IPerfTestRunner {
- final Logger LOGGER = (Logger) LoggerFactory.getLogger(getClass());
-
- @Override
- public void runThroughputTest(final int lines, final Histogram histogram) {
- final long s1 = System.nanoTime();
- final Logger logger = LOGGER;
- for (int j = 0; j < lines; j++) {
- logger.info(THROUGHPUT_MSG);
- }
- final long s2 = System.nanoTime();
- final long opsPerSec = (1000L * 1000L * 1000L * lines) / (s2 - s1);
- histogram.addObservation(opsPerSec);
- }
-
- @Override
- public void runLatencyTest(
- final int samples, final Histogram histogram, final long nanoTimeCost, final int threadCount) {
- final Logger logger = LOGGER;
- for (int i = 0; i < samples; i++) {
- final long s1 = System.nanoTime();
- logger.info(LATENCY_MSG);
- final long s2 = System.nanoTime();
- final long value = s2 - s1 - nanoTimeCost;
- if (value > 0) {
- histogram.addObservation(value);
- }
- // wait 1 microsec
- final long PAUSE_NANOS = 10000 * threadCount;
- final long pauseStart = System.nanoTime();
- while (PAUSE_NANOS > (System.nanoTime() - pauseStart)) {
- // busy spin
- }
- }
- }
-
- @Override
- public void shutdown() {
- ((LifeCycle) LoggerFactory.getILoggerFactory()).stop();
- }
-
- @Override
- public void log(final String msg) {
- LOGGER.info(msg);
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/SimplePerfTest.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/SimplePerfTest.java
deleted file mode 100644
index 11ac9f5801..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/SimplePerfTest.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-import java.lang.management.GarbageCollectorMXBean;
-import java.lang.management.ManagementFactory;
-import java.lang.management.RuntimeMXBean;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.core.async.AsyncLogger;
-import org.apache.logging.log4j.core.async.AsyncLoggerContextSelector;
-
-/**
- * Created by remko on 2/26/2016.
- *
- * -XX:+UnlockDiagnosticVMOptions -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintTenuringDistribution -XX:+PrintGCApplicationConcurrentTime -XX:+PrintGCApplicationStoppedTime
- */
-public class SimplePerfTest {
- static final int ITERATIONS = 100000;
-
- public static void main(final String[] args) throws Exception {
- System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getName());
-
- final Logger logger = LogManager.getLogger();
- if (!(logger instanceof AsyncLogger)) {
- throw new IllegalStateException();
- }
-
- logger.error("Starting...");
- System.out.println("Starting...");
- Thread.sleep(100);
-
- final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
- final long testStartNanos = System.nanoTime();
- final long[] UPTIMES = new long[1024];
- final long[] DURATIONS = new long[1024];
-
- // warmup
- final long startMs = System.currentTimeMillis();
- final long end = startMs + TimeUnit.SECONDS.toMillis(10);
- int warmupCount = 0;
- do {
- runTest(logger, runtimeMXBean, UPTIMES, DURATIONS, warmupCount);
- warmupCount++;
- // Thread.sleep(1000);// drain buffer
- } while (System.currentTimeMillis() < end);
-
- final int COUNT = 10;
- for (int i = 0; i < COUNT; i++) {
- final int count = warmupCount + i;
- runTest(logger, runtimeMXBean, UPTIMES, DURATIONS, count);
- // Thread.sleep(1000);// drain buffer
- }
- final double testDurationNanos = System.nanoTime() - testStartNanos;
- System.out.println("Done. Calculating stats...");
-
- printReport("Warmup", UPTIMES, DURATIONS, 0, warmupCount);
- printReport("Test", UPTIMES, DURATIONS, warmupCount, COUNT);
-
- final StringBuilder sb = new StringBuilder(512);
- sb.append("Test took: ")
- .append(testDurationNanos / (1000.0 * 1000.0 * 1000.0))
- .append(" sec");
- System.out.println(sb);
-
- final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();
- for (int i = 0; i < gcBeans.size(); i++) {
- final GarbageCollectorMXBean gcBean = gcBeans.get(i);
- sb.setLength(0);
- sb.append("GC[").append(gcBean.getName()).append("] ");
- sb.append(gcBean.getCollectionCount()).append(" collections, collection time=");
- sb.append(gcBean.getCollectionTime()).append(" millis.");
- System.out.println(sb);
- }
- }
-
- private static void printReport(
- final String label, final long[] UPTIMES, final long[] DURATIONS, final int offset, final int length) {
- final StringBuilder sb = new StringBuilder(512);
- long total = 0;
- for (int i = offset; i < offset + length; i++) {
- sb.setLength(0);
- final long opsPerSec = (1000L * 1000L * 1000L * ITERATIONS) / DURATIONS[i];
- total += opsPerSec;
- sb.append(UPTIMES[i]).append(" ");
- sb.append(label).append(": Throughput: ").append(opsPerSec).append(" ops/s");
- System.out.println(sb);
- }
- sb.setLength(0);
- sb.append("Average ")
- .append(label)
- .append(" throughput: ")
- .append(total / length)
- .append(" ops/s");
- System.out.println(sb);
-
- sb.setLength(0);
- System.out.println(sb.append(label).append(" ran: ").append(length).append(" iterations"));
- }
-
- private static void runTest(
- final Logger logger,
- final RuntimeMXBean runtimeMXBean,
- final long[] UPTIMES,
- final long[] DURATIONS,
- final int index) {
- UPTIMES[index] = runtimeMXBean.getUptime();
- final long startNanos = System.nanoTime();
- loop(logger, ITERATIONS);
- final long endNanos = System.nanoTime();
- DURATIONS[index] = endNanos - startNanos;
- }
-
- private static void loop(final Logger logger, final int iterations) {
- // String[] arg7 = new String[] {"arg1", "arg2","arg3", "arg4","arg5", "arg6","arg7", };
- // String[] arg2 = new String[] {"arg1", "arg2", };
- //
- for (int i = 0; i < iterations; i++) {
- // logger.error("7 arg message {} {} {} {} {} {} {}");
- // logger.error("7 arg message {} {} ");
-
- logger.error("simple text message");
- }
- }
-}
diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/YieldIdleStrategy.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/YieldIdleStrategy.java
deleted file mode 100644
index 540b7fee56..0000000000
--- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/YieldIdleStrategy.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async.perftest;
-
-/**
- * Idle strategy that yields the thread.
- */
-class YieldIdleStrategy implements IdleStrategy {
-
- /**
- * yields the current thread.
- * @see IdleStrategy
- */
- @Override
- public void idle() {
- Thread.yield();
- }
-}
diff --git a/log4j-core-its/src/test/resources/logback-test.xml b/log4j-core-its/src/test/resources/logback-test.xml
deleted file mode 100644
index 88f97346ad..0000000000
--- a/log4j-core-its/src/test/resources/logback-test.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one or more
- ~ contributor license agreements. See the NOTICE file distributed with
- ~ this work for additional information regarding copyright ownership.
- ~ The ASF licenses this file to you under the Apache License, Version 2.0
- ~ (the "License"); you may not use this file except in compliance with
- ~ the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- -->
-<configuration>
-
- <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
- <encoder>
- <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
- </encoder>
- </appender>
-
- <root level="info">
- <appender-ref ref="STDOUT" />
- </root>
-</configuration>
diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CollectionLoggingTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CollectionLoggingTest.java
deleted file mode 100644
index 9e49c3f185..0000000000
--- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CollectionLoggingTest.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core;
-
-import java.net.NetworkInterface;
-import java.net.SocketException;
-import java.nio.charset.Charset;
-import java.util.HashMap;
-import java.util.Map;
-import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.core.test.appender.ListAppender;
-import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
-import org.apache.logging.log4j.core.test.junit.Named;
-import org.apache.logging.log4j.message.StringMapMessage;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
-import org.junitpioneer.jupiter.ReadsSystemProperty;
-
-@LoggerContextSource("log4j-collectionLogging.xml")
-@Disabled("Work in progress")
-public class CollectionLoggingTest {
-
- private final ListAppender app;
-
- public CollectionLoggingTest(@Named("List") final ListAppender app) {
- this.app = app.clear();
- }
-
- @Test
- @ReadsSystemProperty
- public void testSystemProperties(final LoggerContext context) {
- final Logger logger = context.getLogger(CollectionLoggingTest.class.getName());
- logger.error(System.getProperties());
- // logger.error(new MapMessage(System.getProperties()));
- // TODO: some assertions
- }
-
- @Test
- @ReadsSystemProperty
- public void testSimpleMap(final LoggerContext context) {
- final Logger logger = context.getLogger(CollectionLoggingTest.class.getName());
- logger.error(System.getProperties());
- final Map<String, String> map = new HashMap<>();
- map.put("MyKey1", "MyValue1");
- map.put("MyKey2", "MyValue2");
- logger.error(new StringMapMessage(map));
- logger.error(map);
- // TODO: some assertions
- }
-
- @Test
- public void testNetworkInterfaces(final LoggerContext context) throws SocketException {
- final Logger logger = context.getLogger(CollectionLoggingTest.class.getName());
- logger.error(NetworkInterface.getNetworkInterfaces());
- // TODO: some assertions
- }
-
- @Test
- public void testAvailableCharsets(final LoggerContext context) {
- final Logger logger = context.getLogger(CollectionLoggingTest.class.getName());
- logger.error(Charset.availableCharsets());
- // TODO: some assertions
- }
-}
diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LogEventTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LogEventTest.java
deleted file mode 100644
index 40b3a95ad7..0000000000
--- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LogEventTest.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import org.apache.logging.log4j.Level;
-import org.apache.logging.log4j.core.impl.Log4jLogEvent;
-import org.apache.logging.log4j.message.Message;
-import org.apache.logging.log4j.message.SimpleMessage;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
-
-/**
- *
- */
-public class LogEventTest {
-
- private static final Message MESSAGE = new SimpleMessage("This is a test");
- private static final TestClass TESTER = new TestClass();
-
- @Test
- @Disabled
- public void testEquals() {
- final LogEvent event1 = Log4jLogEvent.newBuilder() //
- .setLoggerName(this.getClass().getName()) //
- .setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
- .setLevel(Level.INFO) //
- .setMessage(new SimpleMessage("Hello, world!")) //
- .build();
- final LogEvent event2 = Log4jLogEvent.newBuilder() //
- .setLoggerName(this.getClass().getName()) //
- .setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
- .setLevel(Level.INFO) //
- .setMessage(new SimpleMessage("Hello, world!")) //
- .build();
- final LogEvent event3 = Log4jLogEvent.newBuilder() //
- .setLoggerName(this.getClass().getName()) //
- .setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
- .setLevel(Level.INFO) //
- .setMessage(new SimpleMessage("Hello, world!")) //
- .build();
- assertNotEquals(event1, event2, "Events should not be equal");
- assertEquals(event2, event3, "Events should be equal");
- }
-
- @Test
- public void testLocation() {
- final StackTraceElement ste = TESTER.getEventSource(this.getClass().getName());
- assertNotNull(ste, "No StackTraceElement");
- assertEquals(this.getClass().getName(), ste.getClassName(), "Incorrect event");
- }
-
- private static class TestClass {
- private static final String FQCN = TestClass.class.getName();
-
- public StackTraceElement getEventSource(final String loggerName) {
- final LogEvent event = Log4jLogEvent.newBuilder()
- .setLoggerName(loggerName)
- .setLoggerFqcn(FQCN)
- .setLevel(Level.INFO)
- .setMessage(MESSAGE)
- .build();
- event.setIncludeLocation(true);
- return event.getSource();
- }
- }
-}
diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FileAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FileAppenderTest.java
index 9e8ee25b7e..72cbc775d9 100644
--- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FileAppenderTest.java
+++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FileAppenderTest.java
@@ -41,12 +41,10 @@ import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.DefaultConfiguration;
import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.apache.logging.log4j.core.layout.PatternLayout;
-import org.apache.logging.log4j.core.util.Integers;
import org.apache.logging.log4j.core.util.Throwables;
import org.apache.logging.log4j.message.SimpleMessage;
import org.apache.logging.log4j.test.junit.CleanUpFiles;
import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
@@ -206,43 +204,6 @@ public class FileAppenderTest {
testMultipleLockingAppenderThreads(true, THREADS, createOnDemand);
}
- @ParameterizedTest
- @ValueSource(booleans = {false, true})
- @Disabled
- public void testMultipleVMs(final boolean createOnDemand) throws Exception {
- final String classPath = System.getProperty("java.class.path");
- final int logEventCount = 10;
- final int processCount = 3;
- final Process[] processes = new Process[processCount];
- final ProcessBuilder[] builders = new ProcessBuilder[processCount];
- for (int index = 0; index < processCount; ++index) {
- builders[index] = new ProcessBuilder(
- "java",
- "-cp",
- classPath,
- ProcessTest.class.getName(),
- "Process " + index,
- Integer.toString(logEventCount),
- "true",
- Boolean.toString(createOnDemand));
- }
- for (int index = 0; index < processCount; ++index) {
- processes[index] = builders[index].start();
- }
- for (int index = 0; index < processCount; ++index) {
- final Process process = processes[index];
- // System.out.println("Process " + index + " exited with " + p.waitFor());
- try (final BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
- String line;
- while ((line = br.readLine()) != null) {
- System.out.println(line);
- }
- }
- process.destroy();
- }
- verifyFile(logEventCount * processCount);
- }
-
private static void writer(
final boolean locking,
final int logEventCount,
@@ -351,30 +312,4 @@ public class FileAppenderTest {
}
}
}
-
- public static class ProcessTest {
-
- public static void main(final String[] args) throws Exception {
-
- if (args.length != 3) {
- System.out.println("Required arguments 'id', 'count' and 'lock' not provided");
- System.exit(-1);
- }
- final String id = args[0];
-
- final int count = Integers.parseInt(args[1]);
-
- if (count <= 0) {
- System.out.println("Invalid count value: " + args[1]);
- System.exit(-1);
- }
- final boolean lock = Boolean.parseBoolean(args[2]);
-
- final boolean createOnDemand = Boolean.parseBoolean(args[2]);
-
- // System.out.println("Got arguments " + id + ", " + count + ", " + lock);
-
- writer(lock, count, id, createOnDemand, true, new DefaultConfiguration());
- }
- }
}
diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/RollingRandomAccessFileAppenderRolloverTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/RollingRandomAccessFileAppenderRolloverTest.java
deleted file mode 100644
index 3c48052c58..0000000000
--- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/RollingRandomAccessFileAppenderRolloverTest.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.appender;
-
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.util.Arrays;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.core.impl.Log4jPropertyKey;
-import org.apache.logging.log4j.core.test.CoreLoggerContexts;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Tag;
-import org.junit.jupiter.api.Test;
-import org.junitpioneer.jupiter.SetSystemProperty;
-
-@Tag("sleepy")
-@SetSystemProperty(key = Log4jPropertyKey.Constant.CONFIG_LOCATION, value = "RollingRandomAccessFileAppenderTest.xml")
-public class RollingRandomAccessFileAppenderRolloverTest {
-
- @Test
- @Disabled
- public void testRollover() throws Exception {
- final File file = new File("target", "RollingRandomAccessFileAppenderTest.log");
- // System.out.println(f.getAbsolutePath());
- final File after1 = new File("target", "afterRollover-1.log");
- file.delete();
- after1.delete();
-
- final Logger log = LogManager.getLogger("com.foo.Bar");
- final String msg = "First a short message that does not trigger rollover";
- log.info(msg);
- Thread.sleep(50);
-
- BufferedReader reader = new BufferedReader(new FileReader(file));
- final String line1 = reader.readLine();
- assertTrue(line1.contains(msg));
- reader.close();
-
- assertFalse(after1.exists(), "afterRollover-1.log not created yet");
-
- String exceed = "Long message that exceeds rollover size... ";
- final char[] padding = new char[250];
- Arrays.fill(padding, 'X');
- exceed += new String(padding);
- log.warn(exceed);
- assertFalse(after1.exists(), "exceeded size but afterRollover-1.log not created yet");
-
- final String trigger = "This message triggers rollover.";
- log.warn(trigger);
- Thread.sleep(100);
- log.warn(trigger);
-
- CoreLoggerContexts.stopLoggerContext(); // stop async thread
- CoreLoggerContexts.stopLoggerContext(false); // stop async thread
-
- final int MAX_ATTEMPTS = 50;
- int count = 0;
- while (!after1.exists() && count++ < MAX_ATTEMPTS) {
- Thread.sleep(50);
- }
-
- assertTrue(after1.exists(), "afterRollover-1.log created");
-
- reader = new BufferedReader(new FileReader(file));
- final String new1 = reader.readLine();
- assertTrue(new1.contains(trigger), "after rollover only new msg");
- assertNull(reader.readLine(), "No more lines");
- reader.close();
- file.delete();
-
- reader = new BufferedReader(new FileReader(after1));
- final String old1 = reader.readLine();
- assertTrue(old1.contains(msg), "renamed file line 1");
- final String old2 = reader.readLine();
- assertTrue(old2.contains(exceed), "renamed file line 2");
- String line = reader.readLine();
- if (line != null) {
- assertTrue(line.contains("This message triggers rollover."), "strange...");
- line = reader.readLine();
- }
- assertNull(line, "No more lines");
- reader.close();
- after1.delete();
- }
-}
diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronOnceADayTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronOnceADayTest.java
deleted file mode 100644
index dcb44f5b8e..0000000000
--- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronOnceADayTest.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.appender.rolling;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.File;
-import java.nio.file.FileSystems;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.time.Duration;
-import java.time.ZonedDateTime;
-import java.util.concurrent.CountDownLatch;
-import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
-import org.apache.logging.log4j.core.util.CronExpression;
-import org.apache.logging.log4j.plugins.Named;
-import org.apache.logging.log4j.status.StatusLogger;
-import org.apache.logging.log4j.test.junit.CleanUpDirectories;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Tag;
-import org.junit.jupiter.api.Test;
-
-@Tag("flaky")
-@Disabled("https://issues.apache.org/jira/browse/LOG4J2-3633")
-public class RollingAppenderCronOnceADayTest extends AbstractRollingListenerTest {
-
- private static final int CRON_DELAY = 10;
- private static final String CONFIG = "log4j-rolling-cron-once-a-day.xml";
- private static final String CONFIG_TARGET = "log4j-rolling-cron-once-a-day-target.xml";
- private static final String TARGET = "target";
- private static final String DIR = TARGET + "/rolling-cron-once-a-day";
- private static final String FILE = DIR + "/rollingtest.log";
- private static final String TARGET_TEST_CLASSES = TARGET + "/test-classes";
-
- private static String cronExpression;
- private static Duration remainingTime;
- private final CountDownLatch rollover = new CountDownLatch(1);
-
- @BeforeAll
- public static void beforeClass() throws Exception {
- final Path src = FileSystems.getDefault().getPath(TARGET_TEST_CLASSES, CONFIG);
- String content = Files.readString(src);
- final ZonedDateTime now = ZonedDateTime.now();
- final ZonedDateTime end = now.plusSeconds(CRON_DELAY);
- remainingTime = Duration.between(now, end);
- cronExpression = String.format("%d %d %d * * ?", end.getSecond(), end.getMinute(), end.getHour());
- content = content.replace("@CRON_EXPR@", cronExpression);
- Files.writeString(Path.of(TARGET_TEST_CLASSES, CONFIG_TARGET), content);
- StatusLogger.getLogger().debug("Cron expression will be " + cronExpression + " in " + remainingTime);
- }
-
- @Test
- @CleanUpDirectories(DIR)
- @LoggerContextSource(value = CONFIG_TARGET, timeout = 10)
- public void testAppender(final Logger logger, @Named("RollingFile") final RollingFileManager manager)
- throws Exception {
- manager.addRolloverListener(this);
- final File file = new File(FILE);
- assertTrue(file.exists(), "Log file does not exist");
- logger.debug("This is test message number 1, waiting for rolling");
-
- final TriggeringPolicy policy = manager.getTriggeringPolicy();
- assertThat(policy).isInstanceOf(CronTriggeringPolicy.class);
- final CronExpression expression = ((CronTriggeringPolicy) policy).getCronExpression();
- assertEquals(cronExpression, expression.getCronExpression(), "Incorrect cron expression");
- logger.debug("Cron expression will be {}", expression.getCronExpression());
-
- // force a rollover
- final long delta = remainingTime.dividedBy(20).toMillis();
- for (int i = 1; i <= 20; ++i) {
- logger.debug("Adding first event {}", i);
- currentTimeMillis.addAndGet(delta);
- }
-
- rollover.await();
- final File dir = new File(DIR);
- assertThat(dir).isNotEmptyDirectory();
-
- for (int i = 1; i < 5; i++) {
- logger.debug("Adding some more event {}", i);
- currentTimeMillis.addAndGet(1000);
- }
- assertThat(dir).isDirectoryContaining("glob:**.gz");
- assertThat(dir.listFiles(pathname -> pathname.getName().endsWith(".gz")))
- .hasSize(1);
- }
-
- @Override
- public void rolloverComplete(final String fileName) {
- rollover.countDown();
- }
-}
diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingDirectSizeTimeNewDirectoryTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingDirectSizeTimeNewDirectoryTest.java
deleted file mode 100644
index bb579a657a..0000000000
--- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingDirectSizeTimeNewDirectoryTest.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.appender.rolling;
-
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.File;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.Phaser;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicLong;
-import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.core.LoggerContext;
-import org.apache.logging.log4j.core.appender.RollingFileAppender;
-import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
-import org.apache.logging.log4j.core.time.Clock;
-import org.apache.logging.log4j.plugins.Factory;
-import org.apache.logging.log4j.plugins.Named;
-import org.apache.logging.log4j.test.junit.CleanUpDirectories;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
-
-/**
- * This test attempts to validate that logging rolls when the file size exceeds 5KB or every second.
- * When the file rolls by time it should create a new directory. When rolling by size it should
- * create multiple files per directory.
- */
-@Disabled("https://issues.apache.org/jira/browse/LOG4J2-3449")
-public class RollingDirectSizeTimeNewDirectoryTest implements RolloverListener {
-
- private static final String CONFIG = "log4j-rolling-size-time-new-directory.xml";
-
- // Note that the path is hardcoded in the configuration!
- private static final String DIR = "target/rolling-size-time-new-directory";
-
- private final Map<String, AtomicInteger> rolloverFiles = new HashMap<>();
- private final AtomicLong currentTimeMillis = new AtomicLong(System.currentTimeMillis());
- private final Phaser phaser = new Phaser(1);
-
- @Factory
- Clock clock() {
- return currentTimeMillis::get;
- }
-
- @Test
- @CleanUpDirectories(DIR)
- @LoggerContextSource(value = CONFIG, timeout = 15)
- public void streamClosedError(final LoggerContext context, @Named("RollingFile") final RollingFileAppender appender)
- throws Exception {
- appender.getManager().addRolloverListener(this);
- final Logger logger = context.getLogger(RollingDirectSizeTimeNewDirectoryTest.class);
-
- for (int i = 0; i < 1000; i++) {
- currentTimeMillis.incrementAndGet();
- logger.info("nHq6p9kgfvWfjzDRYbZp");
- }
- currentTimeMillis.addAndGet(500);
- for (int i = 0; i < 1000; i++) {
- currentTimeMillis.incrementAndGet();
- logger.info("nHq6p9kgfvWfjzDRYbZp");
- }
-
- phaser.arriveAndAwaitAdvance();
-
- assertTrue(rolloverFiles.size() > 1, "A time based rollover did not occur");
- final int maxFiles = Collections.max(rolloverFiles.values(), Comparator.comparing(AtomicInteger::get))
- .get();
- assertTrue(maxFiles > 1, "No size based rollovers occurred");
- }
-
- @Override
- public void rolloverTriggered(final String fileName) {
- phaser.register();
- }
-
- @Override
- public void rolloverComplete(final String fileName) {
- final File file = new File(fileName);
- final String logDir = file.getParentFile().getName();
- final AtomicInteger fileCount = rolloverFiles.computeIfAbsent(logDir, k -> new AtomicInteger(0));
- fileCount.incrementAndGet();
- phaser.arriveAndDeregister();
- }
-}
diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAccessFileManagerHeaderFooterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAccessFileManagerHeaderFooterTest.java
deleted file mode 100644
index c0db1a331e..0000000000
--- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAccessFileManagerHeaderFooterTest.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.appender.rolling;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.nio.charset.Charset;
-import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.core.layout.HtmlLayout;
-import org.apache.logging.log4j.core.test.junit.LoggerContextRule;
-import org.apache.logging.log4j.core.util.Closer;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.RuleChain;
-
-/**
- *
- */
-public class RollingRandomAccessFileManagerHeaderFooterTest {
-
- private static final String CONFIG = "RollingRandomAccessFileAppenderHeaderFooterTest.xml";
- private static final String DIR = "target/RollingRandomAccessFileAppenderHeaderFooterTest/";
- private static final String LOGFILE = "target/RollingRandomAccessFileAppenderHeaderFooterTest.log";
-
- public LoggerContextRule loggerContextRule = LoggerContextRule.createShutdownTimeoutLoggerContextRule(CONFIG);
-
- @Rule
- public RuleChain chain = loggerContextRule.withCleanFoldersRule(DIR);
-
- private Logger logger;
-
- @Before
- public void setUp() throws Exception {
- this.logger = loggerContextRule.getLogger(RollingRandomAccessFileManagerHeaderFooterTest.class.getName());
- }
-
- @Ignore // FIXME
- @Test
- public void testAppender() throws Exception {
- for (int i = 0; i < 8; ++i) {
- logger.debug("This is test message number " + i);
- }
- Thread.sleep(50);
- final File dir = new File(DIR);
- assertTrue("Directory not created: " + dir, dir.exists());
- assertTrue("Directory empty: " + dir, dir.listFiles().length > 0);
- final File[] files = dir.listFiles();
- assertNotNull(files);
- for (final File file : files) {
- assertHeader(file);
- assertFooter(file);
- }
- final File logFile = new File(LOGFILE);
- assertTrue("Expected logfile to exist: " + LOGFILE, logFile.exists());
- assertHeader(logFile);
- }
-
- private void assertHeader(final File file) throws Exception {
- final HtmlLayout layout = HtmlLayout.createDefaultLayout();
- final String header = new String(layout.getHeader(), Charset.defaultCharset());
- final String withoutTimestamp = header.substring(0, 435);
- final String contents = new String(slurp(file), Charset.defaultCharset());
- final String contentsInitialChunk = contents.substring(0, 435);
- assertEquals(file.getName(), withoutTimestamp, contentsInitialChunk);
- }
-
- private void assertFooter(final File file) throws Exception {
- final HtmlLayout layout = HtmlLayout.createDefaultLayout();
- final String footer = new String(layout.getFooter(), Charset.defaultCharset());
- final String contents = new String(slurp(file), Charset.defaultCharset());
- assertTrue(file.getName(), contents.endsWith(footer));
- }
-
- private byte[] slurp(final File file) throws Exception {
- FileInputStream in = null;
- try {
- in = new FileInputStream(file);
- final byte[] result = new byte[(int) file.length()];
- int pos = 0;
- int length = in.read(result);
- while (length > 0) {
- pos += length;
- length = in.read(result, pos, result.length - pos);
- }
- return result;
- } finally {
- Closer.closeSilently(in);
- }
- }
-}
diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTest.java
index 6a59ef7517..99ac7c374f 100644
--- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTest.java
+++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTest.java
@@ -62,12 +62,4 @@ public class AsyncLoggerTest {
assertTrue(LogManager.getFactory().isClassLoaderDependent());
}
-
- // NOTE: only define one @Test method per test class with Async Loggers to prevent spurious failures
- // @Test
- // public void testNanoClockInitiallyDummy() {
- // final AsyncLogger log = (AsyncLogger) LogManager.getLogger("com.foo.Bar");
- // assertTrue(log.getNanoClock() instanceof DummyNanoClock);
- // }
-
}
diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncWaitStrategyFactoryConfigGlobalLoggersTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncWaitStrategyFactoryConfigGlobalLoggersTest.java
deleted file mode 100644
index e9d8742cd6..0000000000
--- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncWaitStrategyFactoryConfigGlobalLoggersTest.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import com.lmax.disruptor.YieldingWaitStrategy;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.core.LoggerContext;
-import org.apache.logging.log4j.core.test.junit.ContextSelectorType;
-import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Tag;
-import org.junit.jupiter.api.Test;
-
-@Tag("async")
-@ContextSelectorType(AsyncLoggerContextSelector.class)
-@LoggerContextSource("AsyncWaitStrategyFactoryConfigGlobalLoggerTest.xml")
-public class AsyncWaitStrategyFactoryConfigGlobalLoggersTest {
-
- @Disabled("This test succeeds when run individually but fails when run by Surefire with all other tests")
- @Test
- public void testConfigWaitStrategyAndFactory() throws Exception {
- final AsyncLogger logger = (AsyncLogger) LogManager.getLogger("com.foo.Bar");
-
- final LoggerContext context = (LoggerContext) LogManager.getContext(false);
- assertTrue(context instanceof AsyncLoggerContext, "context is AsyncLoggerContext");
-
- final AsyncWaitStrategyFactory asyncWaitStrategyFactory =
- context.getConfiguration().getAsyncWaitStrategyFactory();
- assertEquals(
- AsyncWaitStrategyFactoryConfigTest.YieldingWaitStrategyFactory.class,
- asyncWaitStrategyFactory.getClass());
- assertTrue(
- asyncWaitStrategyFactory instanceof AsyncWaitStrategyFactoryConfigTest.YieldingWaitStrategyFactory,
- "factory is YieldingWaitStrategyFactory");
-
- final AsyncLoggerDisruptor delegate = logger.getAsyncLoggerDisruptor();
-
- assertEquals(YieldingWaitStrategy.class, delegate.getWaitStrategy().getClass());
- assertTrue(delegate.getWaitStrategy() instanceof YieldingWaitStrategy, "waitstrategy is YieldingWaitStrategy");
- }
-}
diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/QueueFullAsyncLoggerLoggingFromToStringTest2.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/QueueFullAsyncLoggerLoggingFromToStringTest2.java
deleted file mode 100644
index a7fd20bec0..0000000000
--- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/QueueFullAsyncLoggerLoggingFromToStringTest2.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.async;
-
-import org.apache.logging.log4j.core.LoggerContext;
-import org.apache.logging.log4j.test.junit.SetTestProperty;
-import org.junit.jupiter.api.Disabled;
-
-/**
- * Tests queue full scenarios with pure AsyncLoggers (all loggers async).
- */
-@SetTestProperty(key = "AsyncLogger.formatMsg", value = "true")
-public class QueueFullAsyncLoggerLoggingFromToStringTest2 extends QueueFullAsyncLoggerLoggingFromToStringTest {
-
- @Override
- @Disabled("Causes deadlocks")
- public void testLoggingFromToStringCausesOutOfOrderMessages(LoggerContext ctx, BlockingAppender blockingAppender)
- throws Exception {
- super.testLoggingFromToStringCausesOutOfOrderMessages(ctx, blockingAppender);
- }
-
- @Override
- protected void checkConfig(final LoggerContext ctx) {
- super.checkConfig(ctx);
- assertFormatMessagesInBackground();
- }
-}
diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/xml/XmlSchemaTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/xml/XmlSchemaTest.java
deleted file mode 100644
index 5a71f5fe89..0000000000
--- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/xml/XmlSchemaTest.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.config.xml;
-
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.Arrays;
-import java.util.List;
-import java.util.stream.Stream;
-import javax.xml.XMLConstants;
-import javax.xml.transform.sax.SAXSource;
-import javax.xml.transform.stream.StreamSource;
-import javax.xml.validation.Schema;
-import javax.xml.validation.SchemaFactory;
-import javax.xml.validation.Validator;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.MethodSource;
-import org.xml.sax.Attributes;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXParseException;
-import org.xml.sax.helpers.XMLFilterImpl;
-import org.xml.sax.helpers.XMLReaderFactory;
-
-@Disabled("Schema will be auto-generated in #1954")
-public class XmlSchemaTest {
-
- private static final String TARGET_NAMESPACE = "http://logging.apache.org/log4j/2.0/config";
-
- private static final List<String> IGNORE_CONFIGS = Arrays.asList( //
- "log4j2-arbiters.xml", // Arbiters violate XML schema as they can appear anywhere
- "log4j2-environmentArbiters.xml",
- "log4j2-scriptArbiters.xml",
- "log4j2-systemPropertyArbiters.xml",
- "log4j2-selectArbiters.xml",
- "log4j-core-gctests/src/test/resources/gcFreeLogging.xml", // has 2 <Pattern> tags defined
- "legacy-plugins.xml", //
- "logback", // logback configs
- "log4j-xinclude", //
- "log4j12", // log4j 1.x configs
- "perf-CountingNoOpAppender.xml", // uses test-appender CountingNoOp
- "reconfiguration-deadlock.xml", // uses test-appender ReconfigurationDeadlockTestAppender
- "AsyncWaitStrategy", // uses AsyncWaitStrategyFactory (LOG4J2-3472)
- "XmlConfigurationSecurity.xml", // used for testing XML parser; shouldn't be parseable in secure settings
- "InvalidConfig.xml",
- "InvalidXML.xml");
-
- static Stream<Path> testXmlSchemaValidation() throws IOException {
- return Files.list(Paths.get("src", "test", "resources")).filter(filePath -> {
- final String fileName = filePath.getFileName().toString();
- if (!fileName.endsWith(".xml")) return false;
- for (final String ignore : IGNORE_CONFIGS) {
- if (fileName.contains(ignore)) return false;
- }
- return true;
- });
- }
-
- @ParameterizedTest
- @MethodSource
- public void testXmlSchemaValidation(final Path filePath) throws SAXException, IOException {
- final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
- final Schema schema = factory.newSchema(new StreamSource(getClass().getResourceAsStream("/Log4j-config.xsd")));
- final Validator validator = schema.newValidator();
-
- final XMLFilterImpl namespaceAdder = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) {
- @Override
- public void startElement(
- final String namespace, final String localName, final String qName, final Attributes atts)
- throws SAXException {
- super.startElement(TARGET_NAMESPACE, localName, qName, atts);
- }
- };
-
- final InputSource source = new InputSource(filePath.toAbsolutePath().toString());
- final SAXSource transformedSource = new SAXSource(namespaceAdder, source);
- assertDoesNotThrow(() -> {
- try {
- validator.validate(transformedSource);
- } catch (SAXParseException e) {
- // Wrap the exception to capture the location
- throw new RuntimeException(e.toString(), e);
- }
- });
- }
-}
diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/StoreConfigurationTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/StoreConfigurationTest.java
index 77f41f916b..18c2678def 100644
--- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/StoreConfigurationTest.java
+++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/StoreConfigurationTest.java
@@ -19,14 +19,12 @@ package org.apache.logging.log4j.core.net.ssl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
-@Disabled
-public class StoreConfigurationTest<T extends StoreConfiguration<?>> {
+class StoreConfigurationTest {
@Test
- public void equalsWithNotNullValues() {
+ void equalsWithNotNullValues() {
final String location = "/to/the/file.jks";
final PasswordProvider password = new MemoryPasswordProvider("changeit".toCharArray());
final StoreConfiguration<Object> a = new StoreConfiguration<>(location, password);
@@ -37,7 +35,7 @@ public class StoreConfigurationTest<T extends StoreConfiguration<?>> {
}
@Test
- public void notEqualsWithNullAndNotNullValues() {
+ void notEqualsWithNullAndNotNullValues() {
final String location = "/to/the/file.jks";
final PasswordProvider password = new MemoryPasswordProvider("changeit".toCharArray());
final StoreConfiguration<Object> a = new StoreConfiguration<>(location, password);
@@ -48,7 +46,7 @@ public class StoreConfigurationTest<T extends StoreConfiguration<?>> {
}
@Test
- public void equalsWithNullValues() {
+ void equalsWithNullValues() {
final StoreConfiguration<Object> a = new StoreConfiguration<>(null, new MemoryPasswordProvider(null));
final StoreConfiguration<Object> b = new StoreConfiguration<>(null, new MemoryPasswordProvider(null));
diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/InitTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/InitTest.java
deleted file mode 100644
index 14d9b830ec..0000000000
--- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/InitTest.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to you under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.logging.log4j.core.util;
-
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.test.Timer;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
-
-/**
- * Test initialization.
- */
-@Disabled
-public class InitTest {
-
- @Test
- public void initTest() {
- final Timer timer = new Timer("Log4j Initialization");
- timer.start();
- final Logger logger = LogManager.getLogger();
- timer.stop();
- final long elapsed = timer.getElapsedNanoTime();
- System.out.println(timer.toString());
- assertTrue(elapsed < 1000000000, "Initialization time exceeded threshold; elapsed " + elapsed);
- }
-}
diff --git a/log4j-core-test/src/test/resources/AsyncWaitStrategyFactoryConfigGlobalLoggerTest.xml b/log4j-core-test/src/test/resources/AsyncWaitStrategyFactoryConfigGlobalLoggerTest.xml
deleted file mode 100644
index 7d1802397b..0000000000
--- a/log4j-core-test/src/test/resources/AsyncWaitStrategyFactoryConfigGlobalLoggerTest.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one or more
- ~ contributor license agreements. See the NOTICE file distributed with
- ~ this work for additional information regarding copyright ownership.
- ~ The ASF licenses this file to you under the Apache License, Version 2.0
- ~ (the "License"); you may not use this file except in compliance with
- ~ the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- -->
-<Configuration name="asyncwait-global1" >
-
- <AsyncWaitStrategyFactory
- class="org.apache.logging.log4j.core.async.AsyncWaitStrategyFactoryConfigTest$YieldingWaitStrategyFactory" />
-
- <Appenders>
- <List name="WaitStrategyAppenderList" />
- </Appenders>
-
- <Loggers>
- <Root level="info">
- <AppenderRef ref="WaitStrategyAppenderList"/>
- </Root>
- </Loggers>
-</Configuration>
diff --git a/log4j-core-test/src/test/resources/HttpAppenderTest.xml b/log4j-core-test/src/test/resources/HttpAppenderTest.xml
deleted file mode 100644
index dd82aa5e5b..0000000000
--- a/log4j-core-test/src/test/resources/HttpAppenderTest.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one or more
- ~ contributor license agreements. See the NOTICE file distributed with
- ~ this work for additional information regarding copyright ownership.
- ~ The ASF licenses this file to you under the Apache License, Version 2.0
- ~ (the "License"); you may not use this file except in compliance with
- ~ the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- -->
-<Configuration name="HttpAppenderTest" status="off">
- <Appenders>
- <Console name="Console" target="SYSTEM_OUT">
- <PatternLayout pattern="%d [%t] %-5level: %msg%n%throwable" />
- </Console>
- </Appenders>
- <Loggers>
- <Root level="WARN">
- <AppenderRef ref="Console"/>
- </Root>
- </Loggers>
-</Configuration>
diff --git a/log4j-core-test/src/test/resources/RollingRandomAccessFileAppenderHeaderFooterTest.xml b/log4j-core-test/src/test/resources/RollingRandomAccessFileAppenderHeaderFooterTest.xml
deleted file mode 100644
index 05f3c6dd32..0000000000
--- a/log4j-core-test/src/test/resources/RollingRandomAccessFileAppenderHeaderFooterTest.xml
+++ /dev/null
@@ -1,38 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one or more
- ~ contributor license agreements. See the NOTICE file distributed with
- ~ this work for additional information regarding copyright ownership.
- ~ The ASF licenses this file to you under the Apache License, Version 2.0
- ~ (the "License"); you may not use this file except in compliance with
- ~ the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- -->
-<Configuration status="OFF">
- <Appenders>
- <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="target/RollingRandomAccessFileAppenderHeaderFooterTest.log"
- filePattern="target/RollingRandomAccessFileAppenderHeaderFooterTest/rolled%i.log" append="false"
- immediateFlush="true">
- <HtmlLayout></HtmlLayout>
- <Policies>
- <!--
- <TimeBasedTriggeringPolicy />
- -->
- <SizeBasedTriggeringPolicy size="1024" />
- </Policies>
- </RollingRandomAccessFile>
- </Appenders>
-
- <Loggers>
- <Root level="trace" includeLocation="false">
- <AppenderRef ref="RollingRandomAccessFile"/>
- </Root>
- </Loggers>
-</Configuration>
diff --git a/log4j-core-test/src/test/resources/log4j-collectionLogging.xml b/log4j-core-test/src/test/resources/log4j-collectionLogging.xml
deleted file mode 100644
index 144e25c1ae..0000000000
--- a/log4j-core-test/src/test/resources/log4j-collectionLogging.xml
+++ /dev/null
@@ -1,38 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ~ Licensed to the Apache Software Foundation (ASF) under one or more
- ~ contributor license agreements. See the NOTICE file distributed with
- ~ this work for additional information regarding copyright ownership.
- ~ The ASF licenses this file to you under the Apache License, Version 2.0
- ~ (the "License"); you may not use this file except in compliance with
- ~ the License. You may obtain a copy of the License at
- ~
- ~ http://www.apache.org/licenses/LICENSE-2.0
- ~
- ~ Unless required by applicable law or agreed to in writing, software
- ~ distributed under the License is distributed on an "AS IS" BASIS,
- ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ~ See the License for the specific language governing permissions and
- ~ limitations under the License.
- -->
-<Configuration status="OFF" name="XMLConfigTest">
-
- <Appenders>
- <Console name="STDOUT">
- <PatternLayout pattern="%m%n"/>
- </Console>
- <List name="List">
- </List>
- </Appenders>
-
- <Loggers>
- <Logger name="org.apache.logging.log4j.core" level="error" additivity="false">
- <AppenderRef ref="List"/>
- </Logger>
-
- <Root level="error">
- <AppenderRef ref="STDOUT"/>
- </Root>
- </Loggers>
-
-</Configuration>
diff --git a/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/EcsLayoutTest.java b/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/EcsLayoutTest.java
index 55f351a9ce..79fb109a9b 100644
--- a/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/EcsLayoutTest.java
+++ b/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/EcsLayoutTest.java
@@ -33,7 +33,8 @@ import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@Disabled(
- "`co.elastic.logging.log4j2.EcsLayout` requires `org.apache.logging.log4j.core.layout.AbstractStringLayout#getStringBuilder()`, which doesn't exist anymore")
+ "`co.elastic.logging.log4j2.EcsLayout` requires `org.apache.logging.log4j.core.layout.AbstractStringLayout#getStringBuilder()`, which doesn't exist anymore. "
+ + "This test should be adapted when `co.elastic.logging:log4j2-ecs-layout` publishes a Log4j 3 compatible release.")
class EcsLayoutTest {
private static final Configuration CONFIGURATION = new DefaultConfiguration();
diff --git a/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/LogstashIT.java b/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/LogstashIT.java
index 6f882cea1b..72dfdc37f2 100644
--- a/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/LogstashIT.java
+++ b/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/LogstashIT.java
@@ -68,7 +68,8 @@ import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
@Disabled(
- "`co.elastic.logging.log4j2.EcsLayout` requires `org.apache.logging.log4j.core.layout.AbstractStringLayout#getStringBuilder()`, which doesn't exist anymore")
+ "`co.elastic.logging.log4j2.EcsLayout` requires `org.apache.logging.log4j.core.layout.AbstractStringLayout#getStringBuilder()`, which doesn't exist anymore. "
+ + "This test should be adapted when `co.elastic.logging:log4j2-ecs-layout` publishes a Log4j 3 compatible release.")
@Execution(ExecutionMode.SAME_THREAD)
class LogstashIT {
diff --git a/log4j-perf-test/src/main/java/org/apache/logging/log4j/perf/jmh/AsyncLoggersBenchmark.java b/log4j-perf-test/src/main/java/org/apache/logging/log4j/perf/jmh/AsyncLoggersBenchmark.java
index 36efcc0e82..9772a0b73b 100644
--- a/log4j-perf-test/src/main/java/org/apache/logging/log4j/perf/jmh/AsyncLoggersBenchmark.java
+++ b/log4j-perf-test/src/main/java/org/apache/logging/log4j/perf/jmh/AsyncLoggersBenchmark.java
@@ -72,7 +72,6 @@ public class AsyncLoggersBenchmark {
"org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
System.setProperty(Log4jPropertyKey.ASYNC_LOGGER_RING_BUFFER_SIZE.getSystemKey(), "262144");
System.setProperty(Log4jPropertyKey.ASYNC_LOGGER_WAIT_STRATEGY.getSystemKey(), "Yield");
- // System.setProperty(LoggingSystemProperties.SYSTEM_THREAD_LOCALS_ENABLED, "true");
// System.setProperty(Log4jProperties.ASYNC_LOGGER_FORMAT_MESSAGES_IN_BACKGROUND, "true");
logger = LogManager.getLogger(getClass());
@@ -210,40 +209,4 @@ public class AsyncLoggersBenchmark {
ten,
eleven);
}
-
- // @Benchmark
- // @BenchmarkMode(Mode.SampleTime)
- // @OutputTimeUnit(TimeUnit.NANOSECONDS)
- // public void latencySimple() {
- // logger.info(TEST);
- // }
- //
- // @Benchmark
- // @BenchmarkMode(Mode.SampleTime)
- // @OutputTimeUnit(TimeUnit.NANOSECONDS)
- // public void latency3Params() {
- // logger.info("p1={}, p2={}, p3={}", "1", "2", "3");
- // }
- //
- // @Benchmark
- // @BenchmarkMode(Mode.SampleTime)
- // @OutputTimeUnit(TimeUnit.NANOSECONDS)
- // public void latency5Params() {
- // logger.info("p1={}, p2={}, p3={}, p4={}, p5={}", "1", "2", "3", "4", "5");
- // }
- //
- // @Benchmark
- // @BenchmarkMode(Mode.SampleTime)
- // @OutputTimeUnit(TimeUnit.NANOSECONDS)
- // public void latency7Params() {
- // logger.info("p1={}, p2={}, p3={}, p4={}, p5={}, p6={}, p7={}", "1", "2", "3", "4", "5", "6", "7");
- // }
- //
- // @Benchmark
- // @BenchmarkMode(Mode.SampleTime)
- // @OutputTimeUnit(TimeUnit.NANOSECONDS)
- // public void latency9Params() {
- // logger.info("p1={}, p2={}, p3={}, p4={}, p5={}, p6={}, p7={}, p8={}, p9={}", "1", "2", "3", "4", "5", "6",
- // "7", "8", "9");
- // }
}
diff --git a/pom.xml b/pom.xml
index c140c693d5..26b3c44413 100644
--- a/pom.xml
+++ b/pom.xml
@@ -240,7 +240,6 @@
<module>log4j-config-properties</module>
<module>log4j-config-yaml</module>
<module>log4j-core</module>
- <module>log4j-core-its</module>
<module>log4j-core-test</module>
<module>log4j-csv</module>
<module>log4j-docker</module>