1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.util;
18
19 import org.apache.logging.log4j.core.time.PreciseClock;
20 import org.apache.logging.log4j.status.StatusLogger;
21 import org.apache.logging.log4j.util.PropertiesUtil;
22 import org.apache.logging.log4j.util.Supplier;
23
24 import java.util.HashMap;
25 import java.util.Map;
26
27
28
29
30 public final class ClockFactory {
31
32
33
34
35
36 public static final String PROPERTY_NAME = "log4j.Clock";
37 private static final StatusLogger LOGGER = StatusLogger.getLogger();
38
39
40
41 private ClockFactory() {
42 }
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66 public static Clock getClock() {
67 return createClock();
68 }
69
70 private static Map<String, Supplier<Clock>> aliases() {
71 final Map<String, Supplier<Clock>> result = new HashMap<>();
72 result.put("SystemClock", new Supplier<Clock>() { @Override public Clock get() { return new SystemClock(); } });
73 result.put("SystemMillisClock", new Supplier<Clock>() { @Override public Clock get() { return new SystemMillisClock(); } });
74 result.put("CachedClock", new Supplier<Clock>() { @Override public Clock get() { return CachedClock.instance(); } });
75 result.put("CoarseCachedClock", new Supplier<Clock>() { @Override public Clock get() { return CoarseCachedClock.instance(); } });
76 result.put("org.apache.logging.log4j.core.util.CachedClock", new Supplier<Clock>() { @Override public Clock get() { return CachedClock.instance(); } });
77 result.put("org.apache.logging.log4j.core.util.CoarseCachedClock", new Supplier<Clock>() { @Override public Clock get() { return CoarseCachedClock.instance(); } });
78 return result;
79 }
80
81 private static Clock createClock() {
82 final String userRequest = PropertiesUtil.getProperties().getStringProperty(PROPERTY_NAME);
83 if (userRequest == null) {
84 LOGGER.trace("Using default SystemClock for timestamps.");
85 return logSupportedPrecision(new SystemClock());
86 }
87 final Supplier<Clock> specified = aliases().get(userRequest);
88 if (specified != null) {
89 LOGGER.trace("Using specified {} for timestamps.", userRequest);
90 return logSupportedPrecision(specified.get());
91 }
92 try {
93 final Clock result = Loader.newCheckedInstanceOf(userRequest, Clock.class);
94 LOGGER.trace("Using {} for timestamps.", result.getClass().getName());
95 return logSupportedPrecision(result);
96 } catch (final Exception e) {
97 final String fmt = "Could not create {}: {}, using default SystemClock for timestamps.";
98 LOGGER.error(fmt, userRequest, e);
99 return logSupportedPrecision(new SystemClock());
100 }
101 }
102
103 private static Clock logSupportedPrecision(final Clock clock) {
104 final String support = clock instanceof PreciseClock ? "supports" : "does not support";
105 LOGGER.debug("{} {} precise timestamps.", clock.getClass().getName(), support);
106 return clock;
107 }
108 }