-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Scoped context #2419
Closed
Closed
Scoped context #2419
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
136 changes: 136 additions & 0 deletions
136
log4j-api-test/src/test/java/org/apache/logging/log4j/ResourceLoggerTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,136 @@ | ||
/* | ||
* 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 static org.hamcrest.MatcherAssert.assertThat; | ||
import static org.hamcrest.Matchers.containsString; | ||
import static org.hamcrest.Matchers.hasSize; | ||
import static org.junit.jupiter.api.Assertions.assertTrue; | ||
|
||
import java.util.HashMap; | ||
import java.util.List; | ||
import java.util.Map; | ||
import java.util.concurrent.atomic.AtomicLong; | ||
import java.util.function.Supplier; | ||
import org.apache.logging.log4j.test.TestLogger; | ||
import org.apache.logging.log4j.test.TestLoggerContextFactory; | ||
import org.junit.jupiter.api.BeforeAll; | ||
import org.junit.jupiter.api.Test; | ||
|
||
/** | ||
* Class Description goes here. | ||
*/ | ||
public class ResourceLoggerTest { | ||
@BeforeAll | ||
public static void beforeAll() { | ||
System.setProperty("log4j2.loggerContextFactory", TestLoggerContextFactory.class.getName()); | ||
} | ||
|
||
@Test | ||
public void testFactory() throws Exception { | ||
Connection connection = new Connection("Test", "dummy"); | ||
connection.useConnection(); | ||
MapSupplier mapSupplier = new MapSupplier(connection); | ||
ResourceLogger logger = ResourceLogger.newBuilder() | ||
.withClass(this.getClass()) | ||
.withSupplier(mapSupplier) | ||
.build(); | ||
logger.debug("Hello, {}", "World"); | ||
Logger log = LogManager.getLogger(this.getClass().getName()); | ||
assertTrue(log instanceof TestLogger); | ||
TestLogger testLogger = (TestLogger) log; | ||
List<String> events = testLogger.getEntries(); | ||
assertThat(events, hasSize(1)); | ||
assertThat(events.get(0), containsString("Name=Test")); | ||
assertThat(events.get(0), containsString("Type=dummy")); | ||
assertThat(events.get(0), containsString("Count=1")); | ||
assertThat(events.get(0), containsString("Hello, World")); | ||
events.clear(); | ||
connection.useConnection(); | ||
logger.debug("Used the connection"); | ||
assertThat(events.get(0), containsString("Count=2")); | ||
assertThat(events.get(0), containsString("Used the connection")); | ||
events.clear(); | ||
connection = new Connection("NewConnection", "fiber"); | ||
connection.useConnection(); | ||
mapSupplier = new MapSupplier(connection); | ||
logger = ResourceLogger.newBuilder().withSupplier(mapSupplier).build(); | ||
logger.debug("Connection: {}", "NewConnection"); | ||
assertThat(events, hasSize(1)); | ||
assertThat(events.get(0), containsString("Name=NewConnection")); | ||
assertThat(events.get(0), containsString("Type=fiber")); | ||
assertThat(events.get(0), containsString("Count=1")); | ||
assertThat(events.get(0), containsString("Connection: NewConnection")); | ||
events.clear(); | ||
} | ||
|
||
private static class MapSupplier implements Supplier<Map<String, ?>> { | ||
|
||
private final Connection connection; | ||
|
||
public MapSupplier(final Connection connection) { | ||
this.connection = connection; | ||
} | ||
|
||
@Override | ||
public Map<String, ?> get() { | ||
Map<String, String> map = new HashMap<>(); | ||
map.put("Name", connection.name); | ||
map.put("Type", connection.type); | ||
map.put("Count", Long.toString(connection.getCounter())); | ||
return map; | ||
} | ||
|
||
@Override | ||
public boolean equals(Object o) { | ||
return o instanceof MapSupplier; | ||
} | ||
|
||
@Override | ||
public int hashCode() { | ||
return 77; | ||
} | ||
} | ||
|
||
private static class Connection { | ||
|
||
private final String name; | ||
private final String type; | ||
private final AtomicLong counter = new AtomicLong(0); | ||
|
||
public Connection(final String name, final String type) { | ||
this.name = name; | ||
this.type = type; | ||
} | ||
|
||
public String getName() { | ||
return name; | ||
} | ||
|
||
public String getType() { | ||
return type; | ||
} | ||
|
||
public long getCounter() { | ||
return counter.get(); | ||
} | ||
|
||
public void useConnection() { | ||
counter.incrementAndGet(); | ||
} | ||
} | ||
} |
154 changes: 154 additions & 0 deletions
154
log4j-api-test/src/test/java/org/apache/logging/log4j/ScopedContextTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,154 @@ | ||
/* | ||
* 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 static org.hamcrest.MatcherAssert.assertThat; | ||
import static org.hamcrest.Matchers.equalTo; | ||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
import static org.junit.jupiter.api.Assertions.assertNotEquals; | ||
import static org.junit.jupiter.api.Assertions.assertTrue; | ||
import static org.junit.jupiter.api.Assertions.fail; | ||
|
||
import java.util.concurrent.ArrayBlockingQueue; | ||
import java.util.concurrent.BlockingQueue; | ||
import java.util.concurrent.ExecutionException; | ||
import java.util.concurrent.ExecutorService; | ||
import java.util.concurrent.Future; | ||
import java.util.concurrent.ThreadPoolExecutor; | ||
import java.util.concurrent.TimeUnit; | ||
import java.util.concurrent.atomic.AtomicBoolean; | ||
import java.util.concurrent.atomic.AtomicInteger; | ||
import java.util.concurrent.atomic.AtomicLong; | ||
import org.junit.jupiter.api.Test; | ||
|
||
public class ScopedContextTest { | ||
|
||
@Test | ||
public void testScope() { | ||
ScopedContext.where("key1", "Log4j2").run(() -> assertThat(ScopedContext.get("key1"), equalTo("Log4j2"))); | ||
ScopedContext.where("key1", "value1").run(() -> { | ||
assertThat(ScopedContext.get("key1"), equalTo("value1")); | ||
ScopedContext.where("key2", "value2").run(() -> { | ||
assertThat(ScopedContext.get("key1"), equalTo("value1")); | ||
assertThat(ScopedContext.get("key2"), equalTo("value2")); | ||
}); | ||
}); | ||
} | ||
|
||
@Test | ||
public void testRunWhere() { | ||
ScopedContext.runWhere("key1", "Log4j2", () -> assertThat(ScopedContext.get("key1"), equalTo("Log4j2"))); | ||
ScopedContext.runWhere("key1", "value1", () -> { | ||
assertThat(ScopedContext.get("key1"), equalTo("value1")); | ||
ScopedContext.runWhere("key2", "value2", () -> { | ||
assertThat(ScopedContext.get("key1"), equalTo("value1")); | ||
assertThat(ScopedContext.get("key2"), equalTo("value2")); | ||
}); | ||
}); | ||
} | ||
|
||
@Test | ||
public void testRunThreads() throws Exception { | ||
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(5); | ||
ExecutorService executorService = new ThreadPoolExecutor(1, 2, 30, TimeUnit.SECONDS, workQueue); | ||
final long id = Thread.currentThread().getId(); | ||
final AtomicLong counter = new AtomicLong(0); | ||
ScopedContext.runWhere("key1", "Log4j2", () -> { | ||
assertThat(ScopedContext.get("key1"), equalTo("Log4j2")); | ||
Future<?> future = ScopedContext.runWhere("key2", "value2", executorService, () -> { | ||
assertNotEquals(Thread.currentThread().getId(), id); | ||
assertThat(ScopedContext.get("key1"), equalTo("Log4j2")); | ||
counter.incrementAndGet(); | ||
}); | ||
try { | ||
future.get(); | ||
assertTrue(future.isDone()); | ||
assertEquals(1, counter.get()); | ||
} catch (Exception ex) { | ||
fail("Failed with " + ex.getMessage()); | ||
} | ||
}); | ||
} | ||
|
||
@Test | ||
public void testThreads() throws Exception { | ||
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(5); | ||
ExecutorService executorService = new ThreadPoolExecutor(1, 2, 30, TimeUnit.SECONDS, workQueue); | ||
final long id = Thread.currentThread().getId(); | ||
final AtomicLong counter = new AtomicLong(0); | ||
ScopedContext.where("key1", "Log4j2").run(() -> { | ||
assertThat(ScopedContext.get("key1"), equalTo("Log4j2")); | ||
Future<?> future = ScopedContext.where("key2", "value2").run(executorService, () -> { | ||
assertNotEquals(Thread.currentThread().getId(), id); | ||
assertThat(ScopedContext.get("key1"), equalTo("Log4j2")); | ||
counter.incrementAndGet(); | ||
}); | ||
try { | ||
future.get(); | ||
assertTrue(future.isDone()); | ||
assertEquals(1, counter.get()); | ||
} catch (Exception ex) { | ||
fail("Failed with " + ex.getMessage()); | ||
} | ||
}); | ||
} | ||
|
||
@Test | ||
public void testThreadException() throws Exception { | ||
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(5); | ||
final AtomicBoolean exceptionCaught = new AtomicBoolean(false); | ||
ExecutorService executorService = new ThreadPoolExecutor(1, 2, 30, TimeUnit.SECONDS, workQueue); | ||
long id = Thread.currentThread().getId(); | ||
ScopedContext.runWhere("key1", "Log4j2", () -> { | ||
assertThat(ScopedContext.get("key1"), equalTo("Log4j2")); | ||
Future<?> future = ScopedContext.where("key2", "value2").run(executorService, () -> { | ||
assertNotEquals(Thread.currentThread().getId(), id); | ||
throw new NullPointerException("On purpose NPE"); | ||
}); | ||
try { | ||
future.get(); | ||
} catch (ExecutionException ex) { | ||
assertThat(ex.getMessage(), equalTo("java.lang.NullPointerException: On purpose NPE")); | ||
return; | ||
} catch (Exception ex) { | ||
fail("Failed with " + ex.getMessage()); | ||
} | ||
fail("No exception caught"); | ||
}); | ||
} | ||
|
||
@Test | ||
public void testThreadCall() throws Exception { | ||
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(5); | ||
ExecutorService executorService = new ThreadPoolExecutor(1, 2, 30, TimeUnit.SECONDS, workQueue); | ||
final long id = Thread.currentThread().getId(); | ||
final AtomicInteger counter = new AtomicInteger(0); | ||
int returnVal = ScopedContext.callWhere("key1", "Log4j2", () -> { | ||
assertThat(ScopedContext.get("key1"), equalTo("Log4j2")); | ||
Future<Integer> future = ScopedContext.callWhere("key2", "value2", executorService, () -> { | ||
assertNotEquals(Thread.currentThread().getId(), id); | ||
assertThat(ScopedContext.get("key1"), equalTo("Log4j2")); | ||
return counter.incrementAndGet(); | ||
}); | ||
Integer val = future.get(); | ||
assertTrue(future.isDone()); | ||
assertEquals(1, counter.get()); | ||
return val; | ||
}); | ||
assertThat(returnVal, equalTo(1)); | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nit: good idea to clear this property afterwards.