1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.jcl;
18
19 import java.util.Map;
20 import java.util.WeakHashMap;
21 import java.util.concurrent.ConcurrentHashMap;
22 import java.util.concurrent.ConcurrentMap;
23
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogConfigurationException;
26 import org.apache.commons.logging.LogFactory;
27 import org.apache.logging.log4j.LogManager;
28 import org.apache.logging.log4j.spi.AbstractLogger;
29 import org.apache.logging.log4j.spi.LoggerContext;
30
31
32
33
34 public class LogFactoryImpl extends LogFactory {
35
36 private final Map<LoggerContext, ConcurrentMap<String, Log>> contextMap =
37 new WeakHashMap<LoggerContext, ConcurrentMap<String, Log>>();
38
39 private final ConcurrentMap<String, Object> attributes = new ConcurrentHashMap<String, Object>();
40
41 @Override
42 public Log getInstance(final String name) throws LogConfigurationException {
43 final ConcurrentMap<String, Log> loggers = getLoggersMap();
44 if (loggers.containsKey(name)) {
45 return loggers.get(name);
46 }
47 final org.apache.logging.log4j.Logger logger = PrivateManager.getLogger(name);
48 if (logger instanceof AbstractLogger) {
49 loggers.putIfAbsent(name, new Log4jLog((AbstractLogger) logger, name));
50 return loggers.get(name);
51 }
52 throw new LogConfigurationException(
53 "Commons Logging Adapter requires base logging system to extend Log4j AbstractLogger");
54 }
55
56 private ConcurrentMap<String, Log> getLoggersMap() {
57 final LoggerContext context = PrivateManager.getContext();
58 synchronized (contextMap) {
59 ConcurrentMap<String, Log> map = contextMap.get(context);
60 if (map == null) {
61 map = new ConcurrentHashMap<String, Log>();
62 contextMap.put(context, map);
63 }
64 return map;
65 }
66 }
67
68 @Override
69 public Object getAttribute(final String name) {
70 return attributes.get(name);
71 }
72
73 @Override
74 public String[] getAttributeNames() {
75 return attributes.keySet().toArray(new String[attributes.size()]);
76 }
77
78 @Override
79 public Log getInstance(@SuppressWarnings("rawtypes") final Class clazz) throws LogConfigurationException {
80 return getInstance(clazz.getName());
81 }
82
83
84
85
86
87 @Override
88 public void release() {
89 getLoggersMap().clear();
90 }
91
92 @Override
93 public void removeAttribute(final String name) {
94 attributes.remove(name);
95 }
96
97 @Override
98 public void setAttribute(final String name, final Object value) {
99 if (value != null) {
100 attributes.put(name, value);
101 } else {
102 removeAttribute(name);
103 }
104 }
105
106
107
108
109 private static class PrivateManager extends LogManager {
110 private static final String FQCN = LogFactory.class.getName();
111
112 public static LoggerContext getContext() {
113 return getContext(FQCN, false);
114 }
115
116 public static org.apache.logging.log4j.Logger getLogger(final String name) {
117 return getLogger(FQCN, name);
118 }
119 }
120
121 }