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        }
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     * Creates a new named logger for a given {@link LoggerContext}.
089     *
090     * @param name the name of the logger to create
091     * @param context the LoggerContext this logger will be associated with
092     * @return the new named logger
093     */
094    protected abstract L newLogger(final String name, final LoggerContext context);
095
096    /**
097     * Gets the {@link LoggerContext} that should be used to look up or create loggers. This is similar in spirit to the
098     * {@code ContextSelector} class in {@code log4j-core}. However, implementations can rely on their own framework's
099     * separation of contexts instead (or simply use a singleton).
100     *
101     * @return the LoggerContext to be used for lookup and creation purposes
102     * @see org.apache.logging.log4j.LogManager#getContext(ClassLoader, boolean)
103     * @see org.apache.logging.log4j.LogManager#getContext(String, boolean)
104     */
105    protected abstract LoggerContext getContext();
106
107    /**
108     * Gets the {@link LoggerContext} associated with the given caller class.
109     *
110     * @param callerClass the caller class
111     * @return the LoggerContext for the calling class
112     */
113    protected LoggerContext getContext(final Class<?> callerClass) {
114        ClassLoader cl = null;
115        if (callerClass != null) {
116            cl = callerClass.getClassLoader();
117        }
118        if (cl == null) {
119            cl = LoaderUtil.getThreadContextClassLoader();
120        }
121        return LogManager.getContext(cl, false);
122    }
123
124    @Override
125    public void close() {
126        lock.writeLock ().lock ();
127        try {
128            registry.clear();
129        } finally {
130            lock.writeLock ().unlock ();
131        }
132    }
133}