Skip to content

Centralize initialization in Provider class #2374

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

Merged
merged 4 commits into from
Mar 21, 2024
Merged
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 @@ -75,18 +75,18 @@ protected void log(
sb.append(level.toString());
sb.append(' ');
if (location != null) {
sb.append(location.toString());
sb.append(location);
sb.append(' ');
}
sb.append(message.getFormattedMessage());
final Map<String, String> mdc = ThreadContext.getImmutableContext();
if (mdc.size() > 0) {
if (!mdc.isEmpty()) {
sb.append(' ');
sb.append(mdc.toString());
sb.append(mdc);
sb.append(' ');
}
final Object[] params = message.getParameters();
Throwable t;
final Throwable t;
if (throwable == null
&& params != null
&& params.length > 0
Expand All @@ -99,7 +99,7 @@ protected void log(
sb.append(' ');
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
t.printStackTrace(new PrintStream(baos));
sb.append(baos.toString());
sb.append(baos);
}
list.add(sb.toString());
// System.out.println(sb.toString());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@
*/
public class TestProvider extends Provider {
public TestProvider() {
super(0, "2.6.0", TestLoggerContextFactory.class);
super(5, CURRENT_VERSION, TestLoggerContextFactory.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,8 @@

import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.test.junit.InitializesThreadContext;
import org.apache.logging.log4j.test.junit.SetTestProperty;
import org.apache.logging.log4j.test.junit.UsingThreadContextMap;
import org.junit.jupiter.api.Test;
import org.junitpioneer.jupiter.ClearSystemProperty;

/**
* Tests the {@code DefaultThreadContextMap} class.
Expand Down Expand Up @@ -217,26 +214,4 @@ public void testToStringShowsMapContext() {
map.put("key2", "value2");
assertEquals("{key2=value2}", map.toString());
}

@Test
@ClearSystemProperty(key = DefaultThreadContextMap.INHERITABLE_MAP)
@InitializesThreadContext
public void testThreadLocalNotInheritableByDefault() {
ThreadContextMapFactory.init();
final ThreadLocal<Map<String, String>> threadLocal = DefaultThreadContextMap.createThreadLocalMap(true);
assertFalse(threadLocal instanceof InheritableThreadLocal<?>);
}

@Test
@SetTestProperty(key = DefaultThreadContextMap.INHERITABLE_MAP, value = "true")
@InitializesThreadContext
public void testThreadLocalInheritableIfConfigured() {
ThreadContextMapFactory.init();
try {
final ThreadLocal<Map<String, String>> threadLocal = DefaultThreadContextMap.createThreadLocalMap(true);
assertTrue(threadLocal instanceof InheritableThreadLocal<?>);
} finally {
System.clearProperty(DefaultThreadContextMap.INHERITABLE_MAP);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* 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.spi;

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

import java.time.Duration;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

class ThreadContextMapTest {

private static final String KEY = "key";

static Stream<ThreadContextMap> defaultMaps() {
return Stream.of(
new DefaultThreadContextMap(),
new CopyOnWriteSortedArrayThreadContextMap(),
new GarbageFreeSortedArrayThreadContextMap());
}

static Stream<ThreadContextMap> inheritableMaps() {
final Properties props = new Properties();
props.setProperty("log4j2.isThreadContextMapInheritable", "true");
final PropertiesUtil util = new PropertiesUtil(props);
return Stream.of(
new DefaultThreadContextMap(true, util),
new CopyOnWriteSortedArrayThreadContextMap(util),
new GarbageFreeSortedArrayThreadContextMap(util));
}

@ParameterizedTest
@MethodSource("defaultMaps")
void threadLocalNotInheritableByDefault(final ThreadContextMap contextMap) {
contextMap.put(KEY, "threadLocalNotInheritableByDefault");
verifyThreadContextValueFromANewThread(contextMap, null);
}

@ParameterizedTest
@MethodSource("inheritableMaps")
void threadLocalInheritableIfConfigured(final ThreadContextMap contextMap) {
contextMap.put(KEY, "threadLocalInheritableIfConfigured");
verifyThreadContextValueFromANewThread(contextMap, "threadLocalInheritableIfConfigured");
}

private static void verifyThreadContextValueFromANewThread(
final ThreadContextMap contextMap, final String expected) {
final ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
assertThat(executorService.submit(() -> contextMap.get(KEY)))
.succeedsWithin(Duration.ofSeconds(1))
.isEqualTo(expected);
} finally {
executorService.shutdown();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,36 +16,163 @@
*/
package org.apache.logging.log4j.util;

import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.spi.LoggerContext;
import org.apache.logging.log4j.test.TestLoggerContext;
import static org.assertj.core.api.Assertions.assertThat;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Properties;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.apache.logging.log4j.TestProvider;
import org.apache.logging.log4j.spi.Provider;
import org.apache.logging.log4j.test.TestLogger;
import org.apache.logging.log4j.test.TestLoggerContextFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

@Execution(ExecutionMode.CONCURRENT)
class ProviderUtilTest {

private static final Pattern ERROR_OR_WARNING = Pattern.compile(" (ERROR|WARN) .*", Pattern.DOTALL);

private static final Provider LOCAL_PROVIDER = new LocalProvider();
private static final Provider TEST_PROVIDER = new TestProvider();

private static final Collection<Provider> NO_PROVIDERS = Collections.emptyList();
private static final Collection<Provider> ONE_PROVIDER = Collections.singleton(TEST_PROVIDER);
private static final Collection<Provider> TWO_PROVIDERS = Arrays.asList(LOCAL_PROVIDER, TEST_PROVIDER);

private TestLogger statusLogger;

@BeforeEach
void setup() {
statusLogger = new TestLogger();
}

@Test
void should_have_a_fallback_provider() {
final PropertiesUtil properties = new PropertiesUtil(new Properties());
assertThat(ProviderUtil.selectProvider(properties, NO_PROVIDERS, statusLogger))
.as("check selected provider")
.isNotNull();
// An error for the absence of providers
assertHasErrorOrWarning(statusLogger);
}

public class ProviderUtilTest {
@Test
void should_be_silent_with_a_single_provider() {
final PropertiesUtil properties = new PropertiesUtil(new Properties());
assertThat(ProviderUtil.selectProvider(properties, ONE_PROVIDER, statusLogger))
.as("check selected provider")
.isSameAs(TEST_PROVIDER);
assertNoErrorsOrWarnings(statusLogger);
}

@Test
public void complexTest() throws Exception {
final File file = new File("target/classes");
final ClassLoader classLoader =
new URLClassLoader(new URL[] {file.toURI().toURL()});
final Worker worker = new Worker();
worker.setContextClassLoader(classLoader);
worker.start();
worker.join();
assertTrue(worker.context instanceof TestLoggerContext, "Incorrect LoggerContext");
}

private static class Worker extends Thread {
LoggerContext context = null;

@Override
public void run() {
context = LogManager.getContext(false);
void should_select_provider_with_highest_priority() {
final PropertiesUtil properties = new PropertiesUtil(new Properties());
assertThat(ProviderUtil.selectProvider(properties, TWO_PROVIDERS, statusLogger))
.as("check selected provider")
.isSameAs(TEST_PROVIDER);
// A warning for the presence of multiple providers
assertHasErrorOrWarning(statusLogger);
}

@Test
void should_recognize_log4j_provider_property() {
final Properties map = new Properties();
map.setProperty("log4j.provider", LocalProvider.class.getName());
final PropertiesUtil properties = new PropertiesUtil(map);
assertThat(ProviderUtil.selectProvider(properties, TWO_PROVIDERS, statusLogger))
.as("check selected provider")
.isInstanceOf(LocalProvider.class);
assertNoErrorsOrWarnings(statusLogger);
}

/**
* Can be removed in the future.
*/
@Test
void should_recognize_log4j_factory_property() {
final Properties map = new Properties();
map.setProperty("log4j2.loggerContextFactory", LocalLoggerContextFactory.class.getName());
final PropertiesUtil properties = new PropertiesUtil(map);
assertThat(ProviderUtil.selectProvider(properties, TWO_PROVIDERS, statusLogger)
.getLoggerContextFactory())
.as("check selected logger context factory")
.isInstanceOf(LocalLoggerContextFactory.class);
// Deprecation warning
assertHasErrorOrWarning(statusLogger);
}

/**
* Can be removed in the future.
*/
@Test
void log4j_provider_property_has_priority() {
final Properties map = new Properties();
map.setProperty("log4j.provider", LocalProvider.class.getName());
map.setProperty("log4j2.loggerContextFactory", TestLoggerContextFactory.class.getName());
final PropertiesUtil properties = new PropertiesUtil(map);
assertThat(ProviderUtil.selectProvider(properties, TWO_PROVIDERS, statusLogger))
.as("check selected provider")
.isInstanceOf(LocalProvider.class);
// Warning
assertHasErrorOrWarning(statusLogger);
}

static Stream<Arguments> incorrect_configuration_do_not_throw() {
return Stream.of(
Arguments.of("java.lang.String", null),
Arguments.of("non.existent.Provider", null),
// logger context factory without a matching provider
Arguments.of(null, "org.apache.logging.log4j.util.ProviderUtilTest$LocalLoggerContextFactory"),
Arguments.of(null, "java.lang.String"),
Arguments.of(null, "non.existent.LoggerContextFactory"));
}

@ParameterizedTest
@MethodSource
void incorrect_configuration_do_not_throw(final String provider, final String contextFactory) {
final Properties map = new Properties();
if (provider != null) {
map.setProperty("log4j.provider", provider);
}
if (contextFactory != null) {
map.setProperty("log4j2.loggerContextFactory", contextFactory);
}
final PropertiesUtil properties = new PropertiesUtil(map);
assertThat(ProviderUtil.selectProvider(properties, ONE_PROVIDER, statusLogger))
.as("check selected provider")
.isNotNull();
// Warnings will be present
assertHasErrorOrWarning(statusLogger);
}

public static class LocalLoggerContextFactory extends TestLoggerContextFactory {}

/**
* A provider with a smaller priority than {@link org.apache.logging.log4j.TestProvider}.
*/
public static class LocalProvider extends org.apache.logging.log4j.spi.Provider {
public LocalProvider() {
super(0, CURRENT_VERSION, LocalLoggerContextFactory.class);
}
}

private void assertHasErrorOrWarning(final TestLogger statusLogger) {
assertThat(statusLogger.getEntries()).as("check StatusLogger entries").anySatisfy(entry -> assertThat(entry)
.matches(ERROR_OR_WARNING));
}

private void assertNoErrorsOrWarnings(final TestLogger statusLogger) {
assertThat(statusLogger.getEntries()).as("check StatusLogger entries").allSatisfy(entry -> assertThat(entry)
.doesNotMatch(ERROR_OR_WARNING));
}
}
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
org.apache.logging.log4j.TestProvider
org.apache.logging.log4j.TestProvider
org.apache.logging.log4j.util.ProviderUtilTest.LocalProvider
Loading