1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache license, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the license for the specific language governing permissions and
15 * limitations under the license.
16 */
17 package org.apache.logging.log4j.core.impl;
18
19 import org.apache.logging.log4j.core.LoggerContext;
20 import org.apache.logging.log4j.core.helpers.Constants;
21 import org.apache.logging.log4j.core.helpers.Loader;
22 import org.apache.logging.log4j.core.selector.ClassLoaderContextSelector;
23 import org.apache.logging.log4j.core.selector.ContextSelector;
24 import org.apache.logging.log4j.status.StatusLogger;
25 import org.apache.logging.log4j.spi.LoggerContextFactory;
26
27 /**
28 * Factory to locate a ContextSelector and then load a LoggerContext.
29 */
30 public class Log4jContextFactory implements LoggerContextFactory {
31
32 private static final StatusLogger logger = StatusLogger.getLogger();
33
34 private ContextSelector selector;
35
36 /**
37 * Constructor that initializes the ContextSelector.
38 */
39 public Log4jContextFactory() {
40 String sel = System.getProperty(Constants.LOG4J_CONTEXT_SELECTOR);
41 if (sel != null) {
42 try {
43 Class clazz = Loader.loadClass(sel);
44 if (clazz != null && ContextSelector.class.isAssignableFrom(clazz)) {
45 selector = (ContextSelector) clazz.newInstance();
46 return;
47 }
48 } catch (Exception ex) {
49 logger.error("Unable to create context " + sel, ex);
50 }
51
52 }
53 selector = new ClassLoaderContextSelector();
54 }
55
56 /**
57 * Returns the ContextSelector.
58 * @return The ContextSelector.
59 */
60 public ContextSelector getSelector() {
61 return selector;
62 }
63
64 /**
65 * Load the LoggerContext using the ContextSelector.
66 * @param fqcn The fully qualified class name of the caller.
67 * @param loader The ClassLoader to use or null.
68 * @param currentContext If true returns the current Context, if false returns the Context appropriate
69 * for the caller if a more appropriate Context can be determined.
70 * @return The LoggerContext.
71 */
72 public LoggerContext getContext(String fqcn, ClassLoader loader, boolean currentContext) {
73 LoggerContext ctx = selector.getContext(fqcn, loader, currentContext);
74 if (ctx.getStatus() == LoggerContext.Status.INITIALIZED) {
75 ctx.start();
76 }
77 return ctx;
78 }
79 }