Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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 @@ -27,6 +27,7 @@
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 @@ -85,6 +86,11 @@ protected void log(
sb.append(mdc);
sb.append(' ');
}
if (message instanceof ParameterizedMapMessage) {
sb.append(" Resource 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, String>> {

private final Connection connection;

public MapSupplier(final Connection connection) {
this.connection = connection;
}

@Override
public Map<String, 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));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* 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.message;

import static org.assertj.core.api.Assertions.assertThat;

import org.apache.logging.log4j.test.ListStatusListener;
import org.apache.logging.log4j.test.junit.UsingStatusListener;
import org.junit.jupiter.api.Test;

@UsingStatusListener
class ParameterizedMapMessageTest {

final ListStatusListener statusListener;

ParameterizedMapMessageTest(ListStatusListener statusListener) {
this.statusListener = statusListener;
}

@Test
void testNoArgs() {
final String testMsg = "Test message {}";
ParameterizedMessage msg = new ParameterizedMessage(testMsg, (Object[]) null);
String result = msg.getFormattedMessage();
assertThat(result).isEqualTo(testMsg);
final Object[] array = null;
msg = new ParameterizedMessage(testMsg, array, null);
result = msg.getFormattedMessage();
assertThat(result).isEqualTo(testMsg);
}

@Test
void testZeroLength() {
final String testMsg = "";
ParameterizedMessage msg = new ParameterizedMessage(testMsg, new Object[] {"arg"});
String result = msg.getFormattedMessage();
assertThat(result).isEqualTo(testMsg);
final Object[] array = null;
msg = new ParameterizedMessage(testMsg, array, null);
result = msg.getFormattedMessage();
assertThat(result).isEqualTo(testMsg);
}

@Test
void testOneCharLength() {
final String testMsg = "d";
ParameterizedMessage msg = new ParameterizedMessage(testMsg, new Object[] {"arg"});
String result = msg.getFormattedMessage();
assertThat(result).isEqualTo(testMsg);
final Object[] array = null;
msg = new ParameterizedMessage(testMsg, array, null);
result = msg.getFormattedMessage();
assertThat(result).isEqualTo(testMsg);
}

@Test
void testFormat3StringArgs() {
final String testMsg = "Test message {}{} {}";
final String[] args = {"a", "b", "c"};
final String result = ParameterizedMessage.format(testMsg, args);
assertThat(result).isEqualTo("Test message ab c");
}
}
Loading