下面列出了怎么用org.apache.logging.log4j.core.config.xml.XmlConfiguration的API类实例代码及写法,或者点击链接到github查看源代码。
@BeforeClass
public static void setupClass() {
final File file = new File(STATUS_LOG);
file.delete();
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG);
final LoggerContext ctx = LoggerContext.getContext();
final Configuration config = ctx.getConfiguration();
if (config instanceof XmlConfiguration) {
final String name = config.getName();
if (name == null || !name.equals("XMLConfigTest")) {
ctx.reconfigure();
}
} else {
ctx.reconfigure();
}
}
@Override
public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) {
if (source != null && source != ConfigurationSource.NULL_SOURCE) {
return loggerContext.getExternalContext() != null ? new SOFAConfiguration()
: new XmlConfiguration(loggerContext, source);
}
return null;
}
@Override
public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) {
try {
setLogDir();
setLevel();
String configuration = readLog4jConfiguration(source.getInputStream());
Properties properties = getProperties();
Matcher m = Pattern.compile("\\$\\{(?:ctx:)?([^}]*)\\}").matcher(configuration); //Look for properties in the Log4J2 XML
Map<String, String> substitutions = new HashMap<>();
while (m.find()) {
String key = m.group(1);
String value = resolveValueRecursively(properties, key);
if(value != null) {
substitutions.put(key, value);
}
}
ThreadContext.putAll(substitutions); //Only add the substituted variables to the ThreadContext
//We have to 'reset' the source as the old stream has been read.
return new XmlConfiguration(loggerContext, source.resetInputStream());
} catch (IOException e) {
System.err.println(LOG_PREFIX + "unable to configure Log4J2");
throw new IllegalStateException(LOG_PREFIX + "unable to configure Log4J2", e);
}
}
@Test
public void testReconfiguration() throws Exception {
final Configuration cfg = context.getConfiguration();
assertNotNull("No configuration", cfg);
assertTrue("Not set to default configuration", cfg instanceof DefaultConfiguration);
final File file = new File(CONFIG);
final LoggerContext loggerContext = LoggerContext.getContext(null, false, file.toURI());
assertNotNull("No Logger Context", loggerContext);
final Configuration newConfig = loggerContext.getConfiguration();
assertTrue("Configuration not reset", cfg != newConfig);
assertTrue("Reconfiguration failed", newConfig instanceof XmlConfiguration);
context = LoggerContext.getContext(false);
final Configuration sameConfig = context.getConfiguration();
assertTrue("Configuration should not have been reset", newConfig == sameConfig);
}
private Configuration loadConfiguration(String resourcePath) throws IOException {
InputStream in = getClass().getClassLoader().getResourceAsStream(resourcePath);
try {
Configuration configuration = new XmlConfiguration(new LoggerContext("test"), new ConfigurationSource(in));
configuration.initialize();
configuration.start();
return configuration;
} finally {
in.close();
}
}
@Test
public void testConfig() {
// don't bother using "error" since that's the default; try another level
final LoggerContext ctx = this.init.getLoggerContext();
ctx.reconfigure();
final Configuration config = ctx.getConfiguration();
assertThat(config, instanceOf(XmlConfiguration.class));
for (final StatusListener listener : StatusLogger.getLogger().getListeners()) {
if (listener instanceof StatusConsoleListener) {
assertSame(listener.getStatusLevel(), Level.INFO);
break;
}
}
final Layout<? extends Serializable> layout = PatternLayout.newBuilder()
.setPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN)
.setConfiguration(config)
.build();
// @formatter:off
final FileAppender appender = FileAppender.newBuilder()
.setFileName(LOG_FILE)
.setAppend(false)
.setName("File")
.setIgnoreExceptions(false)
.setBufferSize(4000)
.setBufferedIo(false)
.setLayout(layout)
.build();
// @formatter:on
appender.start();
config.addAppender(appender);
final AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
final AppenderRef[] refs = new AppenderRef[] {ref};
final LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "org.apache.logging.log4j",
"true", refs, null, config, null );
loggerConfig.addAppender(appender, null, null);
config.addLogger("org.apache.logging.log4j", loggerConfig);
ctx.updateLoggers();
final Logger logger = ctx.getLogger(CustomConfigurationTest.class.getName());
logger.info("This is a test");
final File file = new File(LOG_FILE);
assertThat(file, exists());
assertThat(file, hasLength(greaterThan(0L)));
}
/**
* Gets the refresh interval in seconds from the Log4J XML configuration.
*
* @param xmlConfigurationString the XML configuration.
*
* @return the refresh interval in seconds.
* @throws IOException if there were any errors parsing the configuration file.
*/
private int getRefreshIntervalSeconds(String xmlConfigurationString) throws IOException
{
// Create the Log4J configuration object from the configuration string and get the refresh interval in seconds from the configuration.
XmlConfiguration xmlConfiguration =
new XmlConfiguration(loggerContext, new ConfigurationSource(new ByteArrayInputStream(xmlConfigurationString.getBytes(StandardCharsets.UTF_8))));
return xmlConfiguration.getWatchManager().getIntervalSeconds();
}