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.log4j.helpers;
018
019import org.apache.log4j.Appender;
020import org.apache.log4j.spi.AppenderAttachable;
021import org.apache.log4j.spi.LoggingEvent;
022
023import java.util.Collections;
024import java.util.Enumeration;
025import java.util.concurrent.ConcurrentHashMap;
026import java.util.concurrent.ConcurrentMap;
027
028/**
029 * Allows Classes to attach Appenders.
030 */
031public class AppenderAttachableImpl implements AppenderAttachable {
032
033    private final ConcurrentMap<String, Appender> appenders = new ConcurrentHashMap<>();
034
035    @Override
036    public void addAppender(Appender newAppender) {
037        if (newAppender != null) {
038            appenders.put(newAppender.getName(), newAppender);
039        }
040    }
041
042    @Override
043    public Enumeration<Appender> getAllAppenders() {
044        return Collections.enumeration(appenders.values());
045    }
046
047    @Override
048    public Appender getAppender(String name) {
049        return appenders.get(name);
050    }
051
052    @Override
053    public boolean isAttached(Appender appender) {
054        return appenders.containsValue(appender);
055    }
056
057    @Override
058    public void removeAllAppenders() {
059        appenders.clear();
060    }
061
062    @Override
063    public void removeAppender(Appender appender) {
064        appenders.remove(appender.getName(), appender);
065    }
066
067    @Override
068    public void removeAppender(String name) {
069        appenders.remove(name);
070    }
071
072    /**
073     * Call the <code>doAppend</code> method on all attached appenders.
074     * @param event The event to log.
075     * @return The number of appenders.
076     */
077    public int appendLoopOnAppenders(LoggingEvent event) {
078        for (Appender appender : appenders.values()) {
079            appender.doAppend(event);
080        }
081        return appenders.size();
082    }
083
084    public void close() {
085        for (Appender appender : appenders.values()) {
086            appender.close();
087        }
088    }
089}