Skip to content
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
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,16 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.ScopedContext;
import org.apache.logging.log4j.ThreadContext;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.MessageFactory;
import org.apache.logging.log4j.message.ParameterizedMapMessage;
import org.apache.logging.log4j.spi.AbstractLogger;

/**
Expand Down Expand Up @@ -79,12 +82,21 @@ protected void log(
sb.append(' ');
}
sb.append(message.getFormattedMessage());
final Map<String, String> mdc = ThreadContext.getImmutableContext();
Map<String, ScopedContext.Renderable> contextMap = ScopedContext.getContextMap();
final Map<String, String> mdc = new HashMap<>(ThreadContext.getImmutableContext());
if (contextMap != null && !contextMap.isEmpty()) {
contextMap.forEach((key, value) -> mdc.put(key, value.render()));
}
if (!mdc.isEmpty()) {
sb.append(' ');
sb.append(mdc);
sb.append(' ');
}
if (message instanceof ParameterizedMapMessage) {
sb.append(" Map data: ");
sb.append(((ParameterizedMapMessage) message).getData().toString());
sb.append(' ');
}
final Object[] params = message.getParameters();
final Throwable t;
if (throwable == null
Expand Down
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());
Copy link
Member

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.

}

@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();
}
}
}
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));
}
}
Loading
Loading