1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.config;
18
19 import org.apache.logging.log4j.LogManager;
20 import org.apache.logging.log4j.core.LoggerContext;
21 import org.apache.logging.log4j.status.StatusLogger;
22
23 import java.net.URI;
24 import java.net.URISyntaxException;
25
26
27
28
29 public final class Configurator {
30
31 private static final StatusLogger LOGGER = StatusLogger.getLogger();
32
33 private Configurator() {
34 }
35
36
37
38
39
40
41
42
43 public static LoggerContext initialize(final String name, final ClassLoader loader, final String configLocation) {
44
45 try {
46 final URI uri = configLocation == null ? null : new URI(configLocation);
47 return initialize(name, loader, uri);
48 } catch (final URISyntaxException ex) {
49 ex.printStackTrace();
50 }
51 return null;
52 }
53
54
55
56
57
58
59
60
61 public static LoggerContext initialize(final String name, final ClassLoader loader, final URI configLocation) {
62
63 try {
64 org.apache.logging.log4j.spi.LoggerContext context = LogManager.getContext(loader, false, configLocation);
65 if (context instanceof LoggerContext) {
66 final LoggerContext ctx = (LoggerContext) context;
67 final Configuration config = ConfigurationFactory.getInstance().getConfiguration(name, configLocation);
68 ctx.setConfiguration(config);
69 return ctx;
70 } else {
71 LOGGER.error("LogManager returned an instance of {} which does not implement {}. Unable to initialize Log4j",
72 context.getClass().getName(), LoggerContext.class.getName());
73 }
74 } catch (final Exception ex) {
75 ex.printStackTrace();
76 }
77 return null;
78 }
79
80
81
82
83
84
85
86 public static LoggerContext initialize(final ClassLoader loader,
87 final ConfigurationFactory.ConfigurationSource source) {
88
89 try {
90 URI configLocation = null;
91 try {
92 configLocation = source.getLocation() == null ? null : new URI(source.getLocation());
93 } catch (Exception ex) {
94
95 }
96 org.apache.logging.log4j.spi.LoggerContext context = LogManager.getContext(loader, false, configLocation);
97 if (context instanceof LoggerContext) {
98 final LoggerContext ctx = (LoggerContext) context;
99 final Configuration config = ConfigurationFactory.getInstance().getConfiguration(source);
100 ctx.setConfiguration(config);
101 return ctx;
102 } else {
103 LOGGER.error("LogManager returned an instance of {} which does not implement {}. Unable to initialize Log4j",
104 context.getClass().getName(), LoggerContext.class.getName());
105 }
106 } catch (final Exception ex) {
107 ex.printStackTrace();
108 }
109 return null;
110 }
111
112
113
114
115
116 public static void shutdown(final LoggerContext ctx) {
117 if (ctx != null) {
118 ctx.setConfiguration(new DefaultConfiguration());
119 }
120 }
121 }