View Javadoc
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.appender;
18  
19  import java.util.HashMap;
20  import java.util.Map;
21  import java.util.concurrent.locks.Lock;
22  import java.util.concurrent.locks.ReentrantLock;
23  
24  import org.apache.logging.log4j.Level;
25  import org.apache.logging.log4j.Logger;
26  import org.apache.logging.log4j.message.Message;
27  import org.apache.logging.log4j.status.StatusLogger;
28  
29  /**
30   * Abstract base class used to register managers.
31   */
32  public abstract class AbstractManager {
33  
34      /**
35       * Allow subclasses access to the status logger without creating another instance.
36       */
37      protected static final Logger LOGGER = StatusLogger.getLogger();
38  
39      // Need to lock that map instead of using a ConcurrentMap due to stop removing the
40      // manager from the map and closing the stream, requiring the whole stop method to be locked.
41      private static final Map<String, AbstractManager> MAP = new HashMap<>();
42  
43      private static final Lock LOCK = new ReentrantLock();
44  
45      /**
46       * Number of Appenders using this manager.
47       */
48      protected int count;
49  
50      private final String name;
51  
52      protected AbstractManager(final String name) {
53          this.name = name;
54          LOGGER.debug("Starting {} {}", this.getClass().getSimpleName(), name);
55      }
56  
57      /**
58       * Retrieves a Manager if it has been previously created or creates a new Manager.
59       * @param name The name of the Manager to retrieve.
60       * @param factory The Factory to use to create the Manager.
61       * @param data An Object that should be passed to the factory when creating the Manager.
62       * @param <M> The Type of the Manager to be created.
63       * @param <T> The type of the Factory data.
64       * @return A Manager with the specified name and type.
65       */
66      public static <M extends AbstractManager, T> M getManager(final String name, final ManagerFactory<M, T> factory,
67                                                                final T data) {
68          LOCK.lock();
69          try {
70              @SuppressWarnings("unchecked")
71              M manager = (M) MAP.get(name);
72              if (manager == null) {
73                  manager = factory.createManager(name, data);
74                  if (manager == null) {
75                      throw new IllegalStateException("ManagerFactory [" + factory + "] unable to create manager for ["
76                              + name + "] with data [" + data + "]");
77                  }
78                  MAP.put(name, manager);
79              } else {
80                  manager.updateData(data);
81              }
82              manager.count++;
83              return manager;
84          } finally {
85              LOCK.unlock();
86          }
87      }
88  
89      public void updateData(final Object data) {
90      }
91  
92      /**
93       * Determines if a Manager with the specified name exists.
94       * @param name The name of the Manager.
95       * @return True if the Manager exists, false otherwise.
96       */
97      public static boolean hasManager(final String name) {
98          LOCK.lock();
99          try {
100             return MAP.containsKey(name);
101         } finally {
102             LOCK.unlock();
103         }
104     }
105 
106     /**
107      * May be overridden by Managers to perform processing while the Manager is being released and the
108      * lock is held.
109      */
110     protected void releaseSub() {
111     }
112 
113     protected int getCount() {
114         return count;
115     }
116 
117     /**
118      * Called to signify that this Manager is no longer required by an Appender.
119      */
120     public void release() {
121         LOCK.lock();
122         try {
123             --count;
124             if (count <= 0) {
125                 MAP.remove(name);
126                 LOGGER.debug("Shutting down {} {}", this.getClass().getSimpleName(), getName());
127                 releaseSub();
128             }
129         } finally {
130             LOCK.unlock();
131         }
132     }
133 
134     /**
135      * Returns the name of the Manager.
136      * @return The name of the Manager.
137      */
138     public String getName() {
139         return name;
140     }
141 
142     /**
143      * Provide a description of the content format supported by this Manager.  Default implementation returns an empty
144      * (unspecified) Map.
145      *
146      * @return a Map of key/value pairs describing the Manager-specific content format, or an empty Map if no content
147      * format descriptors are specified.
148      */
149     public Map<String, String> getContentFormat() {
150         return new HashMap<>();
151     }
152 
153     protected void log(final Level level, final String message, final Throwable throwable) {
154         final Message m = LOGGER.getMessageFactory().newMessage("{} {} {}: {}",
155                 getClass().getSimpleName(), getName(), message, throwable);
156         LOGGER.log(level, m, throwable);
157     }
158 
159     protected void logDebug(final String message, final Throwable throwable) {
160         log(Level.DEBUG, message, throwable);
161     }
162 
163     protected void logError(final String message, final Throwable throwable) {
164         log(Level.ERROR, message, throwable);
165     }
166 
167     protected void logWarn(final String message, final Throwable throwable) {
168         log(Level.WARN, message, throwable);
169     }
170 
171 }