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.spi;
018
019import java.util.Map;
020import java.util.WeakHashMap;
021import java.util.concurrent.ConcurrentHashMap;
022import java.util.concurrent.ConcurrentMap;
023import java.util.concurrent.locks.ReadWriteLock;
024import java.util.concurrent.locks.ReentrantReadWriteLock;
025
026import org.apache.logging.log4j.LogManager;
027import org.apache.logging.log4j.util.LoaderUtil;
028
029/**
030 * Provides an abstract base class to use for implementing LoggerAdapter.
031 * 
032 * @param <L> the Logger class to adapt
033 * @since 2.1
034 */
035public abstract class AbstractLoggerAdapter<L> implements LoggerAdapter<L> {
036
037    /**
038     * A map to store loggers for their given LoggerContexts.
039     */
040    protected final Map<LoggerContext, ConcurrentMap<String, L>> registry = new WeakHashMap<>();
041
042    private final ReadWriteLock lock = new ReentrantReadWriteLock (true);
043
044    @Override
045    public L getLogger(final String name) {
046        final LoggerContext context = getContext();
047        final ConcurrentMap<String, L> loggers = getLoggersInContext(context);
048        final L logger = loggers.get(name);
049        if (logger != null) {
050            return logger;
051        }
052        loggers.putIfAbsent(name, newLogger(name, context));
053        return loggers.get(name);
054    }
055
056    /**
057     * Gets or creates the ConcurrentMap of named loggers for a given LoggerContext.
058     *
059     * @param context the LoggerContext to get loggers for
060     * @return the map of loggers for the given LoggerContext
061     */
062    public ConcurrentMap<String, L> getLoggersInContext(final LoggerContext context) {
063        ConcurrentMap<String, L> loggers;
064        lock.readLock ().lock ();
065        try {
066            loggers = registry.get (context);
067        } finally {
068            lock.readLock ().unlock ();
069        }
070
071        if (loggers != null) {
072            return loggers;
073        } else {
074            lock.writeLock ().lock ();
075            try {
076                loggers = registry.get (context);
077                if (loggers == null) {
078                    loggers = new ConcurrentHashMap<> ();
079                    registry.put (context, loggers);
080                }
081                return loggers;
082            } finally {
083                lock.writeLock ().unlock ();
084            }
085        }
086    }
087
088    /**
089     * Creates a new named logger for a given {@link LoggerContext}.
090     *
091     * @param name the name of the logger to create
092     * @param context the LoggerContext this logger will be associated with
093     * @return the new named logger
094     */
095    protected abstract L newLogger(final String name, final LoggerContext context);
096
097    /**
098     * Gets the {@link LoggerContext} that should be used to look up or create loggers. This is similar in spirit to the
099     * {@code ContextSelector} class in {@code log4j-core}. However, implementations can rely on their own framework's
100     * separation of contexts instead (or simply use a singleton).
101     *
102     * @return the LoggerContext to be used for lookup and creation purposes
103     * @see org.apache.logging.log4j.LogManager#getContext(ClassLoader, boolean)
104     * @see org.apache.logging.log4j.LogManager#getContext(String, boolean)
105     */
106    protected abstract LoggerContext getContext();
107
108    /**
109     * Gets the {@link LoggerContext} associated with the given caller class.
110     *
111     * @param callerClass the caller class
112     * @return the LoggerContext for the calling class
113     */
114    protected LoggerContext getContext(final Class<?> callerClass) {
115        ClassLoader cl = null;
116        if (callerClass != null) {
117            cl = callerClass.getClassLoader();
118        }
119        if (cl == null) {
120            cl = LoaderUtil.getThreadContextClassLoader();
121        }
122        return LogManager.getContext(cl, false);
123    }
124
125    @Override
126    public void close() {
127        lock.writeLock ().lock ();
128        try {
129            registry.clear();
130        } finally {
131            lock.writeLock ().unlock ();
132        }
133    }
134}