1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.spi;
18
19 import java.util.HashSet;
20 import java.util.Map;
21 import java.util.Set;
22 import java.util.WeakHashMap;
23 import java.util.concurrent.ConcurrentHashMap;
24 import java.util.concurrent.ConcurrentMap;
25 import java.util.concurrent.locks.ReadWriteLock;
26 import java.util.concurrent.locks.ReentrantReadWriteLock;
27
28 import org.apache.logging.log4j.LogManager;
29 import org.apache.logging.log4j.util.LoaderUtil;
30
31
32
33
34
35
36
37 public abstract class AbstractLoggerAdapter<L> implements LoggerAdapter<L>, LoggerContextShutdownAware {
38
39
40
41
42 protected final Map<LoggerContext, ConcurrentMap<String, L>> registry = new ConcurrentHashMap<>();
43
44 private final ReadWriteLock lock = new ReentrantReadWriteLock (true);
45
46 @Override
47 public L getLogger(final String name) {
48 final LoggerContext context = getContext();
49 final ConcurrentMap<String, L> loggers = getLoggersInContext(context);
50 final L logger = loggers.get(name);
51 if (logger != null) {
52 return logger;
53 }
54 loggers.putIfAbsent(name, newLogger(name, context));
55 return loggers.get(name);
56 }
57
58 @Override
59 public void contextShutdown(LoggerContext loggerContext) {
60 registry.remove(loggerContext);
61 }
62
63
64
65
66
67
68
69 public ConcurrentMap<String, L> getLoggersInContext(final LoggerContext context) {
70 ConcurrentMap<String, L> loggers;
71 lock.readLock ().lock ();
72 try {
73 loggers = registry.get (context);
74 } finally {
75 lock.readLock ().unlock ();
76 }
77
78 if (loggers != null) {
79 return loggers;
80 }
81 lock.writeLock ().lock ();
82 try {
83 loggers = registry.get (context);
84 if (loggers == null) {
85 loggers = new ConcurrentHashMap<> ();
86 registry.put (context, loggers);
87 if (context instanceof LoggerContextShutdownEnabled) {
88 ((LoggerContextShutdownEnabled) context).addShutdownListener(this);
89 }
90 }
91 return loggers;
92 } finally {
93 lock.writeLock ().unlock ();
94 }
95 }
96
97
98
99
100 public Set<LoggerContext> getLoggerContexts() {
101 return new HashSet<>(registry.keySet());
102 }
103
104
105
106
107
108
109
110
111 protected abstract L newLogger(final String name, final LoggerContext context);
112
113
114
115
116
117
118
119
120
121
122 protected abstract LoggerContext getContext();
123
124
125
126
127
128
129
130 protected LoggerContext getContext(final Class<?> callerClass) {
131 ClassLoader cl = null;
132 if (callerClass != null) {
133 cl = callerClass.getClassLoader();
134 }
135 if (cl == null) {
136 cl = LoaderUtil.getThreadContextClassLoader();
137 }
138 return LogManager.getContext(cl, false);
139 }
140
141 @Override
142 public void close() {
143 lock.writeLock ().lock ();
144 try {
145 registry.clear();
146 } finally {
147 lock.writeLock ().unlock ();
148 }
149 }
150 }