This is an automated email from the ASF dual-hosted git repository.

rgoers pushed a commit to branch LoggerContextProperties
in repository https://gitbox.apache.org/repos/asf/logging-log4j2.git


The following commit(s) were added to refs/heads/LoggerContextProperties by 
this push:
     new 2eeb4c3d57 Provide LoggerContext properties during configuration
2eeb4c3d57 is described below

commit 2eeb4c3d57eb441ff31cb328e00a7a9f7119cb49
Author: Ralph Goers <[email protected]>
AuthorDate: Mon May 8 22:27:07 2023 -0700

    Provide LoggerContext properties during configuration
---
 .../apache/logging/log4j/spi/LoggerContext.java    |   3 +-
 .../apache/logging/log4j/util/PropertiesUtil.java  |  39 +++--
 .../AsyncLoggerEventTranslationExceptionTest.java  |   1 +
 .../AsyncLoggerTestArgumentFreedOnErrorTest.java   |   1 +
 .../util/NamedLoggerContextPropertiesTest.java     |  65 +++++++
 .../src/test/resources/META-INF/log4j2.my-app.json |  16 ++
 .../apache/logging/log4j/core/LoggerContext.java   |  41 +++--
 .../logging/log4j/core/async/AsyncLogger.java      |   7 +-
 .../log4j/core/config/ConfigurationFactory.java    |   2 +-
 .../core/config/DefaultConfigurationFactory.java   |   5 +-
 .../log4j/core/impl/Log4jContextFactory.java       | 189 +++++++++++++--------
 .../logging/log4j/core/impl/Log4jPropertyKey.java  |   4 +
 .../src/main/resources/log4j2.propertyMapping.json |   1 +
 13 files changed, 267 insertions(+), 107 deletions(-)

diff --git 
a/log4j-api/src/main/java/org/apache/logging/log4j/spi/LoggerContext.java 
b/log4j-api/src/main/java/org/apache/logging/log4j/spi/LoggerContext.java
index 1e3e0f03d2..1c46e90bdb 100644
--- a/log4j-api/src/main/java/org/apache/logging/log4j/spi/LoggerContext.java
+++ b/log4j-api/src/main/java/org/apache/logging/log4j/spi/LoggerContext.java
@@ -19,7 +19,6 @@ package org.apache.logging.log4j.spi;
 import org.apache.logging.log4j.Logger;
 import org.apache.logging.log4j.message.MessageFactory;
 import org.apache.logging.log4j.util.PropertiesUtil;
-import org.apache.logging.log4j.util.PropertyEnvironment;
 
 /**
  * Anchor point for logging implementations.
@@ -51,7 +50,7 @@ public interface LoggerContext {
      * @return the PropertyEnvironment.
      * @since 3.0
      */
-    default PropertyEnvironment getProperties() {
+    default PropertiesUtil getProperties() {
         return 
PropertiesUtil.getContextProperties(LoggerContext.class.getClassLoader(), 
getName());
     }
 
diff --git 
a/log4j-api/src/main/java/org/apache/logging/log4j/util/PropertiesUtil.java 
b/log4j-api/src/main/java/org/apache/logging/log4j/util/PropertiesUtil.java
index bac3111e48..4450e6e9b5 100644
--- a/log4j-api/src/main/java/org/apache/logging/log4j/util/PropertiesUtil.java
+++ b/log4j-api/src/main/java/org/apache/logging/log4j/util/PropertiesUtil.java
@@ -37,8 +37,6 @@ import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentSkipListSet;
 
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.spi.LoggerContext;
 
 /**
  * <em>Consider this class private.</em>
@@ -64,6 +62,8 @@ public class PropertiesUtil implements PropertyEnvironment {
     private static final String LOG4J_SYSTEM_PROPERTIES_FILE_NAME = 
"log4j2.system.properties";
     private static final Lazy<PropertiesUtil> COMPONENT_PROPERTIES = 
Lazy.lazy(PropertiesUtil::new);
 
+    private static final ThreadLocal<PropertiesUtil> environments = new 
InheritableThreadLocal<>();
+
     private final Environment environment;
 
     /**
@@ -137,12 +137,28 @@ public class PropertiesUtil implements 
PropertyEnvironment {
         this.environment = new Environment(contextName, sources);
     }
 
+    public static boolean hasThreadProperties() {
+        return environments.get() != null;
+    }
+
+    public static void setThreadProperties(PropertiesUtil properties) {
+        environments.set(properties);
+    }
+
+    public static void clearThreadProperties() {
+        environments.remove();
+    }
+
     /**
      * Returns the PropertiesUtil used by Log4j.
      *
      * @return the main Log4j PropertiesUtil instance.
      */
     public static PropertiesUtil getProperties() {
+        PropertiesUtil props = environments.get();
+        if (props != null) {
+            return props;
+        }
         return COMPONENT_PROPERTIES.value();
     }
 
@@ -238,21 +254,6 @@ public class PropertiesUtil implements PropertyEnvironment 
{
         environment.reload();
     }
 
-    /**
-     * Locates the PropertyEnvironment for the LoggerContext, if available.
-     * @param classLoader The ClassLoader to use.
-     * @return the located PropertyEnvironment or null if one has not been 
created.
-     */
-    public static PropertyEnvironment locateProperties(ClassLoader 
classLoader) {
-        if (LogManager.getFactory().hasContext(Activator.class.getName(), 
classLoader, false)) {
-            LoggerContext ctx = 
LogManager.getFactory().getContext(Activator.class.getName(),
-                    classLoader, null, false);
-            return ctx.getProperties();
-        } else {
-            return null;
-        }
-    }
-
     /**
      * Get the properties for a LoggerContext just by the name. This ALWAYS 
creates a new PropertiesUtil. Use
      * locateProperties to obtain the current properties.
@@ -285,8 +286,10 @@ public class PropertiesUtil implements PropertyEnvironment 
{
      * @return The PropertiesUtil created.
      */
     public static PropertiesUtil getContextProperties(final ClassLoader 
classLoader, final String contextName) {
-        String filePrefix = META_INF + LOG4J_CONTEXT_PREFIX;
         List<PropertySource> contextSources = new ArrayList<>();
+        String filePrefix = META_INF + LOG4J_PREFIX + contextName + ".";
+        contextSources.addAll(getContextPropertySources(classLoader, 
filePrefix, contextName));
+        filePrefix = META_INF + LOG4J_CONTEXT_PREFIX;
         contextSources.addAll(getContextPropertySources(classLoader, 
filePrefix, contextName));
         contextSources.addAll(getProperties().environment.sources);
         return new PropertiesUtil(contextName, contextSources);
diff --git 
a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerEventTranslationExceptionTest.java
 
b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerEventTranslationExceptionTest.java
index 49ff999e55..458265acb8 100644
--- 
a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerEventTranslationExceptionTest.java
+++ 
b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerEventTranslationExceptionTest.java
@@ -41,6 +41,7 @@ import static org.junit.jupiter.api.Assertions.*;
  */
 @Tag("async")
 @ContextSelectorType(AsyncLoggerContextSelector.class)
+@SetSystemProperty(key = Log4jPropertyKey.Constant.CONFIG_LOCATION, value = 
"log4j2-console.xml")
 @SetSystemProperty(key = 
Log4jPropertyKey.Constant.ASYNC_LOGGER_EXCEPTION_HANDLER_CLASS_NAME,
         value = 
"org.apache.logging.log4j.core.async.AsyncLoggerEventTranslationExceptionTest$TestExceptionHandler")
 class AsyncLoggerEventTranslationExceptionTest {
diff --git 
a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTestArgumentFreedOnErrorTest.java
 
b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTestArgumentFreedOnErrorTest.java
index 3f184a23de..78a20340d0 100644
--- 
a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTestArgumentFreedOnErrorTest.java
+++ 
b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTestArgumentFreedOnErrorTest.java
@@ -32,6 +32,7 @@ import org.junitpioneer.jupiter.SetSystemProperty;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 @Tag("async")
+@SetSystemProperty(key = Log4jPropertyKey.Constant.CONFIG_LOCATION, value = 
"log4j2-console.xml")
 @SetSystemProperty(key = Log4jPropertyKey.Constant.GC_ENABLE_DIRECT_ENCODERS, 
value = "true")
 @SetSystemProperty(key = 
Log4jPropertyKey.Constant.ASYNC_LOGGER_FORMAT_MESSAGES_IN_BACKGROUND, value = 
"true")
 @ContextSelectorType(AsyncLoggerContextSelector.class)
diff --git 
a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/NamedLoggerContextPropertiesTest.java
 
b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/NamedLoggerContextPropertiesTest.java
new file mode 100644
index 0000000000..76bab536b7
--- /dev/null
+++ 
b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/NamedLoggerContextPropertiesTest.java
@@ -0,0 +1,65 @@
+/*
+ * 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 java.net.URI;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.core.LifeCycle;
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.core.config.Configuration;
+import org.apache.logging.log4j.core.impl.Log4jPropertyKey;
+import org.apache.logging.log4j.core.selector.BasicContextSelector;
+import org.apache.logging.log4j.core.test.junit.ContextSelectorType;
+import org.apache.logging.log4j.plugins.Inject;
+import org.apache.logging.log4j.plugins.di.Injector;
+import org.apache.logging.log4j.util.PropertiesUtil;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+@ContextSelectorType(NamedLoggerContextPropertiesTest.TestContextSelector.class)
+public class NamedLoggerContextPropertiesTest {
+
+    @Test
+    public void testProperties() {
+        LoggerContext context = (LoggerContext) LogManager.getContext();
+        assertEquals(LifeCycle.State.STARTED, context.getState());
+        PropertiesUtil props = context.getProperties();
+        assertNotNull(props, "Logger Context Properties were not loaded");
+        String scriptLanguages = 
props.getStringProperty(Log4jPropertyKey.SCRIPT_ENABLE_LANGUAGES);
+        assertEquals("Groovy,JavaScript", scriptLanguages);
+        Configuration config = context.getConfiguration();
+        assertNotNull(config, "Configuration was not created");
+        assertEquals("DSI", config.getName(), "Incorrect configuration name");
+        LogManager.shutdown();
+        assertEquals(LifeCycle.State.STOPPED, context.getState());
+    }
+
+    public class TestContextSelector extends BasicContextSelector {
+
+        @Inject
+        public TestContextSelector(final Injector injector) {
+            super(injector);
+        }
+
+        protected LoggerContext createContext() {
+            return new LoggerContext("my-app", null, (URI) null, injector);
+        }
+    }
+}
diff --git a/log4j-core-test/src/test/resources/META-INF/log4j2.my-app.json 
b/log4j-core-test/src/test/resources/META-INF/log4j2.my-app.json
new file mode 100644
index 0000000000..e616a15ac8
--- /dev/null
+++ b/log4j-core-test/src/test/resources/META-INF/log4j2.my-app.json
@@ -0,0 +1,16 @@
+{
+  "JNDI": {
+    "enableJMS": "true"
+  },
+  "Script": {
+    "enableLanguages": [
+      "Groovy",
+      "JavaScript"
+    ]
+  },
+  "Configuration": {
+    "mergeStrategy": "com.acme.log4j.CustomMergeStrategy",
+    "file": "classpath:log4j-loggerprops.xml",
+    "statusLoggerLevel": "debug"
+  }
+}
diff --git 
a/log4j-core/src/main/java/org/apache/logging/log4j/core/LoggerContext.java 
b/log4j-core/src/main/java/org/apache/logging/log4j/core/LoggerContext.java
index cec9327278..5113cce0f2 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/LoggerContext.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/LoggerContext.java
@@ -57,7 +57,6 @@ import 
org.apache.logging.log4j.spi.LoggerContextShutdownEnabled;
 import org.apache.logging.log4j.spi.LoggerRegistry;
 import org.apache.logging.log4j.spi.Terminable;
 import org.apache.logging.log4j.util.PropertiesUtil;
-import org.apache.logging.log4j.util.PropertyEnvironment;
 
 import static 
org.apache.logging.log4j.core.util.ShutdownCallbackRegistry.SHUTDOWN_HOOK_MARKER;
 
@@ -82,7 +81,7 @@ public class LoggerContext extends AbstractLifeCycle
     private final CopyOnWriteArrayList<PropertyChangeListener> 
propertyChangeListeners = new CopyOnWriteArrayList<>();
     private volatile List<LoggerContextShutdownAware> listeners;
     private final Injector injector;
-    private PropertyEnvironment properties;
+    private PropertiesUtil properties;
 
     /**
      * The Configuration is volatile to guarantee that initialization of the 
Configuration has completed before the
@@ -195,7 +194,7 @@ public class LoggerContext extends AbstractLifeCycle
     }
 
     @Override
-    public PropertyEnvironment getProperties() {
+    public PropertiesUtil getProperties() {
         return properties;
     }
 
@@ -734,19 +733,29 @@ public class LoggerContext extends AbstractLifeCycle
         final ClassLoader cl = externalContext instanceof ClassLoader ? 
(ClassLoader) externalContext : null;
         LOGGER.debug("Reconfiguration started for {} at URI {} with optional 
ClassLoader: {}",
                 this, configURI, cl);
-        final Configuration instance =
-                
injector.getInstance(ConfigurationFactory.KEY).getConfiguration(this, 
contextName, configURI, cl);
-        if (instance == null) {
-            LOGGER.error("Reconfiguration failed: No configuration found for 
'{}' at '{}' in '{}'", contextName, configURI, cl);
-        } else {
-            setConfiguration(instance);
-            /*
-             * instance.start(); Configuration old = 
setConfiguration(instance); updateLoggers(); if (old != null) {
-             * old.stop(); }
-             */
-            final String location = configuration == null ? "?" : 
String.valueOf(configuration.getConfigurationSource());
-            LOGGER.debug("Reconfiguration complete for {} at URI {} with 
optional ClassLoader: {}",
-                    this, location, cl);
+        boolean setProperties = false;
+        if (properties != null && !PropertiesUtil.hasThreadProperties()) {
+            PropertiesUtil.setThreadProperties(properties);
+        }
+        try {
+            final Configuration instance =
+                    
injector.getInstance(ConfigurationFactory.KEY).getConfiguration(this, 
contextName, configURI, cl);
+            if (instance == null) {
+                LOGGER.error("Reconfiguration failed: No configuration found 
for '{}' at '{}' in '{}'", contextName, configURI, cl);
+            } else {
+                setConfiguration(instance);
+                /*
+                 * instance.start(); Configuration old = 
setConfiguration(instance); updateLoggers(); if (old != null) {
+                 * old.stop(); }
+                 */
+                final String location = configuration == null ? "?" : 
String.valueOf(configuration.getConfigurationSource());
+                LOGGER.debug("Reconfiguration complete for {} at URI {} with 
optional ClassLoader: {}",
+                        this, location, cl);
+            }
+        } finally {
+            if (setProperties) {
+                PropertiesUtil.clearThreadProperties();
+            }
         }
     }
 
diff --git 
a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLogger.java 
b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLogger.java
index bb16428ac0..d1aaada126 100644
--- 
a/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLogger.java
+++ 
b/log4j-core/src/main/java/org/apache/logging/log4j/core/async/AsyncLogger.java
@@ -223,7 +223,12 @@ public class AsyncLogger extends Logger implements 
EventTranslatorVararg<RingBuf
         final RingBufferLogEventTranslator translator = getCachedTranslator();
         initTranslator(translator, fqcn, location, level, marker, message, 
thrown);
         initTranslatorThreadValues(translator);
-        publish(translator);
+        try {
+            publish(translator);
+        } catch (Throwable ex) {
+            translator.clear();
+            throw ex;
+        }
     }
 
     private void publish(final RingBufferLogEventTranslator translator) {
diff --git 
a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java
 
b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java
index 77d633e45c..77ce1bde6e 100644
--- 
a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java
+++ 
b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java
@@ -114,7 +114,7 @@ public abstract class ConfigurationFactory extends 
ConfigurationBuilderFactory {
     }
 
     public static AuthorizationProvider authorizationProvider(final 
PropertyEnvironment props) {
-        final String authClass = props.getStringProperty(PREFIXES, 
"authorizationProvider", null);
+        final String authClass = 
props.getStringProperty(Log4jPropertyKey.CONFIG_AUTH_PROVIDER);
         AuthorizationProvider provider = null;
         if (authClass != null) {
             try {
diff --git 
a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/DefaultConfigurationFactory.java
 
b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/DefaultConfigurationFactory.java
index bac9909d6f..fbeb66ca19 100644
--- 
a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/DefaultConfigurationFactory.java
+++ 
b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/DefaultConfigurationFactory.java
@@ -65,7 +65,10 @@ public class DefaultConfigurationFactory extends 
ConfigurationFactory {
     public Configuration getConfiguration(final LoggerContext loggerContext, 
final String name, final URI configLocation) {
 
         if (configLocation == null) {
-            final PropertyEnvironment properties = 
PropertiesUtil.getProperties();
+            PropertyEnvironment properties = loggerContext.getProperties();
+            if (properties == null) {
+                properties = PropertiesUtil.getProperties();
+            }
             final String configLocationStr =
                     
substitutor.replace(properties.getStringProperty(Log4jPropertyKey.CONFIG_LOCATION));
             if (configLocationStr != null) {
diff --git 
a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/Log4jContextFactory.java
 
b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/Log4jContextFactory.java
index 6b1ca5ff5a..e720bf36bb 100644
--- 
a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/Log4jContextFactory.java
+++ 
b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/Log4jContextFactory.java
@@ -166,10 +166,7 @@ public class Log4jContextFactory implements 
LoggerContextFactory, ShutdownCallba
             ctx.setExternalContext(externalContext);
         }
         if (ctx.getState() == LifeCycle.State.INITIALIZED) {
-            if (ctx.getProperties() == null) {
-                
ctx.setProperties(PropertiesUtil.getContextProperties(classLoader, 
ctx.getName()));
-            }
-            ctx.start();
+            startContext(ctx, classLoader);
         }
         return ctx;
     }
@@ -194,18 +191,25 @@ public class Log4jContextFactory implements 
LoggerContextFactory, ShutdownCallba
         if (ctx.getState() == LifeCycle.State.INITIALIZED) {
             if (source != null) {
                 ContextAnchor.THREAD_CONTEXT.set(ctx);
-                if (ctx.getProperties() == null) {
-                    
ctx.setProperties(PropertiesUtil.getContextProperties(classLoader, 
ctx.getName()));
+                boolean setProperties = false;
+                try {
+                    if (ctx.getProperties() == null) {
+                        PropertiesUtil props = 
PropertiesUtil.getContextProperties(classLoader, ctx.getName());
+                        ctx.setProperties(props);
+                        PropertiesUtil.setThreadProperties(props);
+                        setProperties = true;
+                    }
+                    final Configuration config = 
injector.getInstance(ConfigurationFactory.KEY).getConfiguration(ctx, source);
+                    LOGGER.debug("Starting {} from configuration {}", ctx, 
source);
+                    ctx.start(config);
+                } finally {
+                    if (setProperties) {
+                        PropertiesUtil.clearThreadProperties();
+                    }
+                    ContextAnchor.THREAD_CONTEXT.remove();
                 }
-                final Configuration config = 
injector.getInstance(ConfigurationFactory.KEY).getConfiguration(ctx, source);
-                LOGGER.debug("Starting {} from configuration {}", ctx, source);
-                ctx.start(config);
-                ContextAnchor.THREAD_CONTEXT.remove();
             } else {
-                if (ctx.getProperties() == null) {
-                    
ctx.setProperties(PropertiesUtil.getContextProperties(classLoader, 
ctx.getName()));
-                }
-                ctx.start();
+                startContext(ctx, classLoader);
             }
         }
         return ctx;
@@ -230,12 +234,19 @@ public class Log4jContextFactory implements 
LoggerContextFactory, ShutdownCallba
         }
         if (ctx.getState() == LifeCycle.State.INITIALIZED) {
             ContextAnchor.THREAD_CONTEXT.set(ctx);
+            boolean setProperties = false;
             try {
                 if (ctx.getProperties() == null) {
-                    
ctx.setProperties(PropertiesUtil.getContextProperties(classLoader, 
ctx.getName()));
+                    PropertiesUtil props = 
PropertiesUtil.getContextProperties(classLoader, ctx.getName());
+                    ctx.setProperties(props);
+                    PropertiesUtil.setThreadProperties(props);
+                    setProperties = true;
                 }
                 ctx.start(configuration);
             } finally {
+                if (setProperties) {
+                    PropertiesUtil.clearThreadProperties();
+                }
                 ContextAnchor.THREAD_CONTEXT.remove();
             }
         }
@@ -266,19 +277,26 @@ public class Log4jContextFactory implements 
LoggerContextFactory, ShutdownCallba
         if (ctx.getState() == LifeCycle.State.INITIALIZED) {
             if (configLocation != null || name != null) {
                 ContextAnchor.THREAD_CONTEXT.set(ctx);
-                if (ctx.getProperties() == null) {
-                    
ctx.setProperties(PropertiesUtil.getContextProperties(classLoader, name));
+                boolean setProperties = false;
+                try {
+                    if (ctx.getProperties() == null) {
+                        PropertiesUtil props = 
PropertiesUtil.getContextProperties(classLoader, ctx.getName());
+                        ctx.setProperties(props);
+                        PropertiesUtil.setThreadProperties(props);
+                        setProperties = true;
+                    }
+                    final Configuration config =
+                            
injector.getInstance(ConfigurationFactory.KEY).getConfiguration(ctx, name, 
configLocation);
+                    LOGGER.debug("Starting {} from configuration at {}", ctx, 
configLocation);
+                    ctx.start(config);
+                } finally {
+                    if (setProperties) {
+                        PropertiesUtil.clearThreadProperties();
+                    }
+                    ContextAnchor.THREAD_CONTEXT.remove();
                 }
-                final Configuration config =
-                        
injector.getInstance(ConfigurationFactory.KEY).getConfiguration(ctx, name, 
configLocation);
-                LOGGER.debug("Starting {} from configuration at {}", ctx, 
configLocation);
-                ctx.start(config);
-                ContextAnchor.THREAD_CONTEXT.remove();
             } else {
-                if (ctx.getProperties() == null) {
-                    
ctx.setProperties(PropertiesUtil.getContextProperties(classLoader, name));
-                }
-                ctx.start();
+                startContext(ctx, classLoader);
             }
         }
         return ctx;
@@ -293,20 +311,27 @@ public class Log4jContextFactory implements 
LoggerContextFactory, ShutdownCallba
         }
         if (ctx.getState() == LifeCycle.State.INITIALIZED) {
             if (configLocation != null || name != null) {
-                if (ctx.getProperties() == null) {
-                    
ctx.setProperties(PropertiesUtil.getContextProperties(classLoader, name));
+                boolean setProperties = false;
+                try {
+                    if (ctx.getProperties() == null) {
+                        PropertiesUtil props = 
PropertiesUtil.getContextProperties(classLoader, ctx.getName());
+                        ctx.setProperties(props);
+                        PropertiesUtil.setThreadProperties(props);
+                        setProperties = true;
+                    }
+                    ContextAnchor.THREAD_CONTEXT.set(ctx);
+                    final Configuration config =
+                            
injector.getInstance(ConfigurationFactory.KEY).getConfiguration(ctx, name, 
configLocation);
+                    LOGGER.debug("Starting {} from configuration at {}", ctx, 
configLocation);
+                    ctx.start(config);
+                } finally {
+                    if (setProperties) {
+                        PropertiesUtil.clearThreadProperties();
+                    }
+                    ContextAnchor.THREAD_CONTEXT.remove();
                 }
-                ContextAnchor.THREAD_CONTEXT.set(ctx);
-                final Configuration config =
-                        
injector.getInstance(ConfigurationFactory.KEY).getConfiguration(ctx, name, 
configLocation);
-                LOGGER.debug("Starting {} from configuration at {}", ctx, 
configLocation);
-                ctx.start(config);
-                ContextAnchor.THREAD_CONTEXT.remove();
             } else {
-                if (ctx.getProperties() == null) {
-                    
ctx.setProperties(PropertiesUtil.getContextProperties(classLoader, name));
-                }
-                ctx.start();
+                startContext(ctx, classLoader);
             }
         }
         return ctx;
@@ -326,47 +351,75 @@ public class Log4jContextFactory implements 
LoggerContextFactory, ShutdownCallba
         if (ctx.getState() == LifeCycle.State.INITIALIZED) {
             if ((configLocations != null && !configLocations.isEmpty())) {
                 ContextAnchor.THREAD_CONTEXT.set(ctx);
-                final List<AbstractConfiguration> configurations = new 
ArrayList<>(configLocations.size());
-                if (ctx.getProperties() == null) {
-                    
ctx.setProperties(PropertiesUtil.getContextProperties(classLoader, name));
-                }
-                for (final URI configLocation : configLocations) {
-                    final Configuration currentReadConfiguration = 
injector.getInstance(ConfigurationFactory.KEY)
-                            .getConfiguration(ctx, name, configLocation);
-                    if (currentReadConfiguration != null) {
-                        if (currentReadConfiguration instanceof 
DefaultConfiguration) {
-                            LOGGER.warn("Unable to locate configuration {}, 
ignoring", configLocation.toString());
-                        }
-                        else if (currentReadConfiguration instanceof 
AbstractConfiguration) {
-                            configurations.add((AbstractConfiguration) 
currentReadConfiguration);
+                boolean setProperties = false;
+                try {
+                    final List<AbstractConfiguration> configurations = new 
ArrayList<>(configLocations.size());
+                    if (ctx.getProperties() == null) {
+                        PropertiesUtil props = 
PropertiesUtil.getContextProperties(classLoader, ctx.getName());
+                        ctx.setProperties(props);
+                        PropertiesUtil.setThreadProperties(props);
+                        setProperties = true;
+                    }
+                    for (final URI configLocation : configLocations) {
+                        final Configuration currentReadConfiguration = 
injector.getInstance(ConfigurationFactory.KEY)
+                                .getConfiguration(ctx, name, configLocation);
+                        if (currentReadConfiguration != null) {
+                            if (currentReadConfiguration instanceof 
DefaultConfiguration) {
+                                LOGGER.warn("Unable to locate configuration 
{}, ignoring", configLocation.toString());
+                            } else if (currentReadConfiguration instanceof 
AbstractConfiguration) {
+                                configurations.add((AbstractConfiguration) 
currentReadConfiguration);
+                            } else {
+                                LOGGER.error(
+                                        "Found configuration {}, which is not 
an AbstractConfiguration and can't be handled by CompositeConfiguration",
+                                        configLocation);
+                            }
                         } else {
-                            LOGGER.error(
-                                    "Found configuration {}, which is not an 
AbstractConfiguration and can't be handled by CompositeConfiguration",
-                                    configLocation);
+                            LOGGER.info("Unable to access configuration {}, 
ignoring", configLocation.toString());
                         }
+                    }
+                    if (configurations.size() == 0) {
+                        LOGGER.error("No configurations could be created for 
{}", configLocations.toString());
+                    } else if (configurations.size() == 1) {
+                        ctx.start(configurations.get(0));
                     } else {
-                        LOGGER.info("Unable to access configuration {}, 
ignoring", configLocation.toString());
+                        final CompositeConfiguration compositeConfiguration = 
new CompositeConfiguration(configurations);
+                        ctx.start(compositeConfiguration);
                     }
+                } finally {
+                    if (setProperties) {
+                        PropertiesUtil.clearThreadProperties();
+                    }
+                    ContextAnchor.THREAD_CONTEXT.remove();
                 }
-                if (configurations.size() == 0) {
-                    LOGGER.error("No configurations could be created for {}", 
configLocations.toString());
-                } else if (configurations.size() == 1) {
-                    ctx.start(configurations.get(0));
-                } else {
-                    final CompositeConfiguration compositeConfiguration = new 
CompositeConfiguration(configurations);
-                    ctx.start(compositeConfiguration);
-                }
-                ContextAnchor.THREAD_CONTEXT.remove();
             } else {
-                if (ctx.getProperties() == null) {
-                    
ctx.setProperties(PropertiesUtil.getContextProperties(classLoader, name));
-                }
-                ctx.start();
+                startContext(ctx, classLoader);
             }
         }
         return ctx;
     }
 
+    private void startContext(LoggerContext ctx, ClassLoader classLoader) {
+        boolean setProperties = false;
+        try {
+            if (ctx.getProperties() == null) {
+                PropertiesUtil props = 
PropertiesUtil.getContextProperties(classLoader, ctx.getName());
+                ctx.setProperties(props);
+                PropertiesUtil.setThreadProperties(props);
+                setProperties = true;
+            }
+            final Configuration config = 
injector.getInstance(ConfigurationFactory.KEY).getConfiguration(ctx, 
ctx.getName(), null);
+            if (config != null) {
+                ctx.start(config);
+            } else {
+                ctx.start();
+            }
+        } finally {
+            if (setProperties) {
+                PropertiesUtil.clearThreadProperties();
+            }
+        }
+    }
+
     @Override
     public void shutdown(final String fqcn, final ClassLoader loader, final 
boolean currentContext, final boolean allContexts) {
         if (selector.hasContext(fqcn, loader, currentContext)) {
diff --git 
a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/Log4jPropertyKey.java
 
b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/Log4jPropertyKey.java
index e71dcd1ad2..57969298da 100644
--- 
a/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/Log4jPropertyKey.java
+++ 
b/log4j-core/src/main/java/org/apache/logging/log4j/core/impl/Log4jPropertyKey.java
@@ -41,6 +41,7 @@ public enum Log4jPropertyKey implements PropertyKey {
     ASYNC_LOGGER_THREAD_NAME_STRATEGY(PropertyComponent.ASYNC_LOGGER, 
Constant.THREAD_NAME_STRATEGY),
     ASYNC_LOGGER_TIMEOUT(PropertyComponent.ASYNC_LOGGER, Constant.TIMEOUT),
     ASYNC_LOGGER_WAIT_STRATEGY(PropertyComponent.ASYNC_LOGGER, 
Constant.WAIT_STRATEGY),
+    CONFIG_AUTH_PROVIDER(PropertyComponent.CONFIGURATION, 
Constant.AUTH_PROVIDER),
     CONFIG_CLOCK(PropertyComponent.CONFIGURATION, Constant.CLOCK),
     CONFIG_CONFIGURATION_FACTORY_CLASS_NAME(PropertyComponent.CONFIGURATION, 
Constant.CONFIGURATION_FACTORY),
     CONFIG_DEFAULT_LEVEL(PropertyComponent.CONFIGURATION, Constant.LEVEL),
@@ -175,6 +176,9 @@ public enum Log4jPropertyKey implements PropertyKey {
                 + PropertyComponent.Constant.ASYNC_LOGGER + DELIM + TIMEOUT;
         public static final String ASYNC_LOGGER_WAIT_STRATEGY = 
LoggingSystemProperty.SYSTEM_PROPERTY_PREFIX
                 + PropertyComponent.Constant.ASYNC_LOGGER + DELIM + 
WAIT_STRATEGY;
+        static final String AUTH_PROVIDER = "authorizationProvider";
+        public static final String CONFIG_AUTH_PROVIDER = 
LoggingSystemProperty.SYSTEM_PROPERTY_PREFIX
+                + PropertyComponent.CONFIGURATION + DELIM + AUTH_PROVIDER;
         static final String CLOCK = "clock";
         public static final String CONFIG_CLOCK = 
LoggingSystemProperty.SYSTEM_PROPERTY_PREFIX
                 + PropertyComponent.Constant.CONFIGURATION + DELIM + CLOCK;
diff --git a/log4j-core/src/main/resources/log4j2.propertyMapping.json 
b/log4j-core/src/main/resources/log4j2.propertyMapping.json
index 04ea043961..0da2aca044 100644
--- a/log4j-core/src/main/resources/log4j2.propertyMapping.json
+++ b/log4j-core/src/main/resources/log4j2.propertyMapping.json
@@ -9,6 +9,7 @@
     "asyncLoggerConfigRingBufferSize": ["AsyncLoggerConfig", "ringBufferSize"],
     "asyncLoggerConfigWaitStrategy": ["AsyncLoggerConfig", "waitStrategy"],
     "asyncQueueFullPolicy": ["AsyncLogger", "queueFullPolicy"],
+    "authorizationProvider": ["Configuration", "authorizationProvider"],
     "clock": ["Configuration", "clock"],
     "Configuration.allowedProtocols": ["Configuration", "allowedProtocols"],
     "Configuration.authorizationProvider": ["Configuration", 
"authorizationProvider"],


Reply via email to