001/*
002 * Copyright (C) 2019 Michael N. Lipp (http://www.mnl.de)
003 * 
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *        http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package de.mnl.osgi.log4j2osgi;
018
019import de.mnl.osgi.lf4osgi.core.LoggerGroup;
020import org.apache.logging.log4j.message.MessageFactory;
021import org.apache.logging.log4j.spi.ExtendedLogger;
022import org.apache.logging.log4j.spi.LoggerContext;
023import org.apache.logging.log4j.spi.LoggerRegistry;
024import org.osgi.framework.Bundle;
025
026/**
027 * The OsgiLoggerContext.
028 */
029public class OsgiLoggerContext implements LoggerGroup, LoggerContext {
030
031    private final Bundle bundle;
032    private final LoggerRegistry<OsgiLogger> loggerRegistry;
033
034    /**
035     * Instantiates a new OSGi logger context.
036     *
037     * @param bundle the bundle
038     */
039    public OsgiLoggerContext(Bundle bundle) {
040        this.bundle = bundle;
041        loggerRegistry = new LoggerRegistry<>();
042    }
043
044    @Override
045    public Bundle getBundle() {
046        return bundle;
047    }
048
049    @Override
050    public OsgiLogger getLogger(final String name) {
051        if (!loggerRegistry.hasLogger(name)) {
052            loggerRegistry.putIfAbsent(name, null,
053                new OsgiLogger(this, name));
054        }
055        return loggerRegistry.getLogger(name);
056    }
057
058    @Override
059    public ExtendedLogger getLogger(final String name,
060            final MessageFactory messageFactory) {
061        if (!loggerRegistry.hasLogger(name, messageFactory)) {
062            loggerRegistry.putIfAbsent(name, messageFactory,
063                new OsgiLogger(this, name, messageFactory));
064        }
065        return loggerRegistry.getLogger(name, messageFactory);
066    }
067
068    @Override
069    public boolean hasLogger(final String name) {
070        return loggerRegistry.hasLogger(name);
071    }
072
073    @Override
074    public boolean hasLogger(final String name,
075            final MessageFactory messageFactory) {
076        return loggerRegistry.hasLogger(name, messageFactory);
077    }
078
079    @Override
080    public boolean hasLogger(final String name,
081            final Class<? extends MessageFactory> messageFactoryClass) {
082        return loggerRegistry.hasLogger(name, messageFactoryClass);
083    }
084
085    @Override
086    public Object getExternalContext() {
087        return null;
088    }
089
090}