001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.core.selector;
018
019import java.net.URI;
020import java.util.ArrayList;
021import java.util.Collections;
022import java.util.List;
023import java.util.Map;
024import java.util.concurrent.ConcurrentHashMap;
025import java.util.concurrent.ConcurrentMap;
026import javax.naming.NamingException;
027
028import org.apache.logging.log4j.core.LoggerContext;
029import org.apache.logging.log4j.core.impl.ContextAnchor;
030import org.apache.logging.log4j.core.net.JndiManager;
031import org.apache.logging.log4j.core.util.Constants;
032import org.apache.logging.log4j.status.StatusLogger;
033
034/**
035 * This class can be used to define a custom logger repository. It makes use of the fact that in J2EE environments, each
036 * web-application is guaranteed to have its own JNDI context relative to the <code>java:comp/env</code> context. In
037 * EJBs, each enterprise bean (albeit not each application) has its own context relative to the
038 * <code>java:comp/env</code> context. An <code>env-entry</code> in a deployment descriptor provides the information to
039 * the JNDI context. Once the <code>env-entry</code> is set, a repository selector can query the JNDI application
040 * context to look up the value of the entry. The logging context of the web-application will depend on the value the
041 * env-entry. The JNDI context which is looked up by this class is <code>java:comp/env/log4j/context-name</code>.
042 *
043 * <p>
044 * Here is an example of an <code>env-entry</code>:
045 * </p>
046 * <blockquote>
047 * 
048 * <pre>
049 * &lt;env-entry&gt;
050 *   &lt;description&gt;JNDI logging context name for this app&lt;/description&gt;
051 *   &lt;env-entry-name&gt;log4j/context-name&lt;/env-entry-name&gt;
052 *   &lt;env-entry-value&gt;aDistinctiveLoggingContextName&lt;/env-entry-value&gt;
053 *   &lt;env-entry-type&gt;java.lang.String&lt;/env-entry-type&gt;
054 * &lt;/env-entry&gt;
055 * </pre>
056 * 
057 * </blockquote>
058 *
059 * <p>
060 * <em>If multiple applications use the same logging context name, then they
061 * will share the same logging context.</em>
062 * </p>
063 *
064 * <p>
065 * You can also specify the URL for this context's configuration resource. This repository selector
066 * (ContextJNDISelector) will use this resource to automatically configure the log4j repository.
067 * </p>
068 ** <blockquote>
069 * 
070 * <pre>
071 * &lt;env-entry&gt;
072 *   &lt;description&gt;URL for configuring log4j context&lt;/description&gt;
073 *   &lt;env-entry-name&gt;log4j/configuration-resource&lt;/env-entry-name&gt;
074 *   &lt;env-entry-value&gt;urlOfConfigurationResource&lt;/env-entry-value&gt;
075 *   &lt;env-entry-type&gt;java.lang.String&lt;/env-entry-type&gt;
076 * &lt;/env-entry&gt;
077 * </pre>
078 * 
079 * </blockquote>
080 *
081 * <p>
082 * It usually good practice for configuration resources of distinct applications to have distinct names. However, if
083 * this is not possible Naming
084 * </p>
085 */
086public class JndiContextSelector implements NamedContextSelector {
087
088    private static final LoggerContext CONTEXT = new LoggerContext("Default");
089
090    private static final ConcurrentMap<String, LoggerContext> CONTEXT_MAP =
091        new ConcurrentHashMap<String, LoggerContext>();
092
093    private static final StatusLogger LOGGER = StatusLogger.getLogger();
094
095    public JndiContextSelector() {
096        if (!JndiManager.isJndiContextSelectorEnabled()) {
097            throw new IllegalStateException("JNDI must be enabled by setting log4j2.enableJndiContextSelector=true");
098        }
099    }
100
101    @Override
102    public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext) {
103        return getContext(fqcn, loader, currentContext, null);
104    }
105
106    @Override
107    public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext,
108                                    final URI configLocation) {
109
110        final LoggerContext lc = ContextAnchor.THREAD_CONTEXT.get();
111        if (lc != null) {
112            return lc;
113        }
114
115        String loggingContextName = null;
116
117        final JndiManager jndiManager = JndiManager.getDefaultManager();
118        try {
119            loggingContextName = jndiManager.lookup(Constants.JNDI_CONTEXT_NAME);
120        } catch (final NamingException ne) {
121            LOGGER.error("Unable to lookup {}", Constants.JNDI_CONTEXT_NAME, ne);
122        } finally {
123            jndiManager.release();
124        }
125
126        return loggingContextName == null ? CONTEXT : locateContext(loggingContextName, null, configLocation);
127    }
128
129    @Override
130    public LoggerContext locateContext(final String name, final Object externalContext, final URI configLocation) {
131        if (name == null) {
132            LOGGER.error("A context name is required to locate a LoggerContext");
133            return null;
134        }
135        if (!CONTEXT_MAP.containsKey(name)) {
136            final LoggerContext ctx = new LoggerContext(name, externalContext, configLocation);
137            CONTEXT_MAP.putIfAbsent(name, ctx);
138        }
139        return CONTEXT_MAP.get(name);
140    }
141
142    @Override
143    public void removeContext(final LoggerContext context) {
144
145        for (final Map.Entry<String, LoggerContext> entry : CONTEXT_MAP.entrySet()) {
146            if (entry.getValue().equals(context)) {
147                CONTEXT_MAP.remove(entry.getKey());
148            }
149        }
150    }
151
152    @Override
153    public LoggerContext removeContext(final String name) {
154        return CONTEXT_MAP.remove(name);
155    }
156
157    @Override
158    public List<LoggerContext> getLoggerContexts() {
159        final List<LoggerContext> list = new ArrayList<LoggerContext>(CONTEXT_MAP.values());
160        return Collections.unmodifiableList(list);
161    }
162
163}