下面列出了org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration#org.apache.logging.log4j.core.config.Configurator 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void givenDefaultLog4j2Environment_whenProgrammaticallyConfigured_thenLogsCorrectly() {
ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
AppenderComponentBuilder console = builder.newAppender("Stdout", "CONSOLE")
.addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
console.add(builder.newLayout("PatternLayout")
.addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable"));
builder.add(console);
builder.add(builder.newLogger("com", Level.DEBUG)
.add(builder.newAppenderRef("Stdout"))
.addAttribute("additivity", false));
builder.add(builder.newRootLogger(Level.ERROR)
.add(builder.newAppenderRef("Stdout")));
Configurator.initialize(builder.build());
LogPrinter logPrinter = new LogPrinter();
logPrinter.printlog();
}
public void initializeSuperSpecialDebugFeatures() {
if (SPECIAL_DEBUG_MODE) {
return;
}
SystrayHelper.showInfoMessage("Switching to debug mode");
deadlockDetector = new ThreadDeadlockDetector();
deadlockDetector.addListener(new DefaultDeadlockListener());
Configurator.setAllLevels(LogManager.getRootLogger().getName(), Level.DEBUG);
logger.debug("==========================");
logger.debug("==DEBUG MODE ESTABLISHED==");
logger.debug("==========================");
logger.debug("---------System Information---------");
logger.debug("Operating System: " + System.getProperty("os.name") + " (" + System.getProperty("os.version") + "/" + System.getProperty("os.arch") + ")");
logger.debug("Java: " + System.getProperty("java.vendor") + " " + System.getProperty("java.version") + " (" + System.getProperty("java.home") + ")");
logger.debug("Working Dir: " + System.getProperty("user.dir"));
logger.debug("------------------------------------");
SPECIAL_DEBUG_MODE = true;
}
@Test
public void testConfig() {
try (final LoggerContext ctx = Configurator.initialize("Test1",
"target/test-classes/log4j2-dynamicfilter.xml")) {
final Configuration config = ctx.getConfiguration();
final Filter filter = config.getFilter();
assertNotNull("No DynamicThresholdFilter", filter);
assertTrue("Not a DynamicThresholdFilter", filter instanceof DynamicThresholdFilter);
final DynamicThresholdFilter dynamic = (DynamicThresholdFilter) filter;
final String key = dynamic.getKey();
assertNotNull("Key is null", key);
assertEquals("Incorrect key value", "loginId", key);
final Map<String, Level> map = dynamic.getLevelMap();
assertNotNull("Map is null", map);
assertEquals("Incorrect number of map elements", 1, map.size());
}
}
@Test
public void testExceptionInTaskListenerTaskStarted() {
// disable printing of exception below
Logger logger = LogManager.getLogger(GTaskManager.class);
Configurator.setLevel(logger.getName(), Level.OFF);
gTaskManager.addTaskListener(new GTaskListenerAdapter() {
@Override
public void taskStarted(GScheduledTask task) {
throw new RuntimeException("Test Exception");
}
});
gTaskManager.scheduleTask(new SimpleTask("Task 5"), 20, true);
// this is testing that the exception does cause the taskManager to timeout still busy
waitForTaskManager();
Configurator.setLevel(logger.getName(), Level.DEBUG);
}
@Test
public void debugChangeLevelsChildLoggers() {
final org.apache.logging.log4j.Logger loggerChild = context.getLogger(logger.getName() + ".child");
// Use logger AND loggerChild
logger.debug("Debug message 1");
loggerChild.debug("Debug message 1 child");
assertEventCount(app.getEvents(), 2);
Configurator.setLevel(logger.getName(), Level.ERROR);
Configurator.setLevel(loggerChild.getName(), Level.DEBUG);
logger.debug("Debug message 2");
loggerChild.debug("Debug message 2 child");
assertEventCount(app.getEvents(), 3);
Configurator.setLevel(logger.getName(), Level.DEBUG);
logger.debug("Debug message 3");
loggerChild.debug("Debug message 3 child");
assertEventCount(app.getEvents(), 5);
}
/**
* Creates new logger with given configuration {@code cfgFile}.
*
* @param cfgFile Log4j configuration XML file.
* @throws IgniteCheckedException Thrown in case logger can't be created.
*/
public Log4J2Logger(File cfgFile) throws IgniteCheckedException {
if (cfgFile == null)
throw new IgniteCheckedException("Configuration XML file for Log4j must be specified.");
if (!cfgFile.exists() || cfgFile.isDirectory())
throw new IgniteCheckedException("Log4j2 configuration path was not found or is a directory: " + cfgFile);
final String path = cfgFile.getAbsolutePath();
addConsoleAppenderIfNeeded(new C1<Boolean, Logger>() {
@Override public Logger apply(Boolean init) {
if (init)
Configurator.initialize(LogManager.ROOT_LOGGER_NAME, path);
return (Logger)LogManager.getRootLogger();
}
});
quiet = quiet0;
cfg = cfgFile.getPath();
}
static void test(final String[] args, final String config) {
// System.out.println(System.getProperty("java.class.path"));
try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderNoAnsiStyleLayoutMain.class.getName(),
config)) {
LOG.fatal("Fatal message.");
LOG.error("Error message.");
LOG.warn("Warning message.");
LOG.info("Information message.");
LOG.debug("Debug message.");
LOG.trace("Trace message.");
logThrowableFromMethod();
// This will log the stack trace as well:
final IOException ioException = new IOException("test");
LOG.error("Error message {}", "Hi", ioException);
final Throwable t = new IOException("test suppressed");
t.addSuppressed(new IOException("test suppressed 2", ioException));
LOG.error("Error message {}, suppressed?", "Hi", t);
LOG.error("Error message {}, suppressed?", "Hi", new IOException("test", t));
}
}
@Test
public void test5LevelPropSetLevel() {
String name = "log4j.test.new_logger_level_set";
Configurator.setLevel(name, org.apache.logging.log4j.Level.DEBUG);
assertLogLevel(name, java.util.logging.Level.FINE);
test5LevelPropFromConfigFile(); // the rest should be untouched!
name = "log4j.Log4jBridgeHandlerTest.propagate1.nested1";
Configurator.setLevel(name, org.apache.logging.log4j.Level.WARN);
assertLogLevel(name, java.util.logging.Level.WARNING);
// the others around should be untouched
assertLogLevel("log4j.Log4jBridgeHandlerTest.propagate1", java.util.logging.Level.FINE);
assertLogLevel("log4j.Log4jBridgeHandlerTest.propagate1.nested2.deeplyNested", java.util.logging.Level.WARNING);
// note: no need to check for the other set[Root]Level() methods, because they all call
// loggerContext.updateLoggers() which calls firePropertyChangeEvent()
}
@Test
public void debugChangeLevelsMapChildLoggers() {
logger.debug("Debug message 1");
loggerChild.debug("Debug message 1 C");
loggerGrandchild.debug("Debug message 1 GC");
assertEventCount(app.getEvents(), 3);
final Map<String, Level> map = new HashMap<>();
map.put(logger.getName(), Level.OFF);
map.put(loggerChild.getName(), Level.DEBUG);
map.put(loggerGrandchild.getName(), Level.WARN);
Configurator.setLevel(map);
logger.debug("Debug message 2");
loggerChild.debug("Debug message 2 C");
loggerGrandchild.debug("Debug message 2 GC");
assertEventCount(app.getEvents(), 4);
map.put(logger.getName(), Level.DEBUG);
map.put(loggerChild.getName(), Level.OFF);
map.put(loggerGrandchild.getName(), Level.DEBUG);
Configurator.setLevel(map);
logger.debug("Debug message 3");
loggerChild.debug("Debug message 3 C");
loggerGrandchild.debug("Debug message 3 GC");
assertEventCount(app.getEvents(), 6);
}
@Test
void log4j2LevelMetrics() {
new Log4j2Metrics().bindTo(registry);
assertThat(registry.get("log4j2.events").counter().count()).isEqualTo(0.0);
Logger logger = LogManager.getLogger(Log4j2MetricsTest.class);
Configurator.setLevel(Log4j2MetricsTest.class.getName(), Level.INFO);
logger.info("info");
logger.warn("warn");
logger.fatal("fatal");
logger.error("error");
logger.debug("debug"); // shouldn't record a metric as per log level config
logger.trace("trace"); // shouldn't record a metric as per log level config
assertThat(registry.get("log4j2.events").tags("level", "info").counter().count()).isEqualTo(1.0);
assertThat(registry.get("log4j2.events").tags("level", "warn").counter().count()).isEqualTo(1.0);
assertThat(registry.get("log4j2.events").tags("level", "fatal").counter().count()).isEqualTo(1.0);
assertThat(registry.get("log4j2.events").tags("level", "error").counter().count()).isEqualTo(1.0);
assertThat(registry.get("log4j2.events").tags("level", "debug").counter().count()).isEqualTo(0.0);
assertThat(registry.get("log4j2.events").tags("level", "trace").counter().count()).isEqualTo(0.0);
}
public static void main(final String[] args) {
System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable
// System.out.println(System.getProperty("java.class.path"));
final String config = args.length == 0 ? "target/test-classes/log4j2-272.xml" : args[0];
try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) {
LOG.fatal("Fatal message.");
LOG.error("Error message.");
LOG.warn("Warning message.");
LOG.info("Information message.");
LOG.debug("Debug message.");
LOG.trace("Trace message.");
try {
throw new NullPointerException();
} catch (final Exception e) {
LOG.error("Error message.", e);
LOG.catching(Level.ERROR, e);
}
LOG.warn("this is ok \n And all \n this have only\t\tblack colour \n and here is colour again?");
LOG.info("Information message.");
}
}
@Test
public void testBuildConfiguration() throws Exception {
try {
System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
"org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory
.newConfigurationBuilder();
CustomConfigurationFactory.addTestFixtures("config name", builder);
final Configuration configuration = builder.build();
try (LoggerContext ctx = Configurator.initialize(configuration)) {
validate(configuration);
}
} finally {
System.getProperties().remove(Constants.LOG4J_CONTEXT_SELECTOR);
}
}
/**
* @param name
* the name of the java class or java package to set the log
* level for
* @param logLevelToSet
* the log level to set e.g. TRACE, DEBUG, INFO, WARN, ERROR and
* FATAL, providing any other value will lead to DEBUG as new log
* level
*/
@MCRCommand(syntax = "change log level of {0} to {1}",
help = "{0} the package or class name for which to change the log level, {1} the log level to set.",
order = 10)
public static synchronized void changeLogLevel(String name, String logLevelToSet) {
LOGGER.info("Setting log level for \"{}\" to \"{}\"", name, logLevelToSet);
Level newLevel = Level.getLevel(logLevelToSet);
if (newLevel == null) {
LOGGER.error("Unknown log level \"{}\"", logLevelToSet);
return;
}
Logger log = "ROOT".equals(name) ? LogManager.getRootLogger() : LogManager.getLogger(name);
if (log == null) {
LOGGER.error("Could not get logger for \"{}\"", name);
return;
}
LOGGER.info("Change log level from {} to {}", log.getLevel(), newLevel);
Configurator.setLevel(log.getName(), newLevel);
}
private void configureLogging(LogLevel logLevel) {
Level log4jLogLevel;
switch (Objects.requireNonNull(logLevel)) {
case NORMAL: {
log4jLogLevel = Level.INFO;
break;
}
case VERBOSE: {
log4jLogLevel = Level.DEBUG;
break;
}
case TRACE: {
log4jLogLevel = Level.TRACE;
break;
}
default: {
throw new IllegalArgumentException("Unknown log level: " + logLevel.name());
}
}
Configurator.setLevel("bt", log4jLogLevel);
}
public static void main(@NotNull final String[] args) throws ParseException, SQLException
{
final Options options = new Options();
CopyNumberAnalyser.addCmdLineArgs(options);
final CommandLineParser parser = new DefaultParser();
final CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption(LOG_DEBUG))
{
Configurator.setRootLevel(Level.DEBUG);
}
String outputDir = formOutputPath(cmd.getOptionValue(DATA_OUTPUT_DIR));
final DatabaseAccess dbAccess = cmd.hasOption(DB_URL) ? databaseAccess(cmd) : null;
CopyNumberAnalyser cnAnalyser = new CopyNumberAnalyser(outputDir, dbAccess);
cnAnalyser.loadConfig(cmd);
cnAnalyser.runAnalysis();
cnAnalyser.close();
LNX_LOGGER.info("CN analysis complete");
}
private String doPost(IPipeLineSession session) throws PipeRunException {
Object formLogIntermediaryResultsObject = session.get("logIntermediaryResults");
boolean formLogIntermediaryResults = ("on".equals((String) formLogIntermediaryResultsObject) ? true : false);
String formLogLevel = (String) session.get("logLevel");
Object formLengthLogRecordsObject = session.get("lengthLogRecords");
int formLengthLogRecords = (formLengthLogRecordsObject != null
? Integer.parseInt((String) formLengthLogRecordsObject) : -1);
HttpServletRequest httpServletRequest = (HttpServletRequest) session.get(IPipeLineSession.HTTP_REQUEST_KEY);
String commandIssuedBy = HttpUtils.getCommandIssuedBy(httpServletRequest);
String msg = "LogLevel changed from [" + retrieveLogLevel() + "] to [" + formLogLevel
+ "], logIntermediaryResults from [" + retrieveLogIntermediaryResults() + "] to [" + ""
+ formLogIntermediaryResults + "] and logMaxMessageLength from [" + retrieveLengthLogRecords()
+ "] to [" + "" + formLengthLogRecords + "] by" + commandIssuedBy;
log.warn(msg);
secLog.info(msg);
IbisMaskingLayout.setMaxLength(formLengthLogRecords);
AppConstants.getInstance().setProperty("log.logIntermediaryResults",
Boolean.toString(formLogIntermediaryResults));
Configurator.setLevel(LogUtil.getRootLogger().getName(), Level.toLevel(formLogLevel));
return retrieveFormInput(session, true);
}
private void initializeNonJndi(final String location) {
if (this.name == null) {
this.name = this.servletContext.getServletContextName();
LOGGER.debug("Using the servlet context name \"{}\".", this.name);
}
if (this.name == null) {
this.name = this.servletContext.getContextPath();
LOGGER.debug("Using the servlet context context-path \"{}\".", this.name);
}
if (this.name == null && location == null) {
LOGGER.error("No Log4j context configuration provided. This is very unusual.");
this.name = new SimpleDateFormat("yyyyMMdd_HHmmss.SSS").format(new Date());
}
if (location != null && location.contains(",")) {
final List<URI> uris = getConfigURIs(location);
this.loggerContext = Configurator.initialize(this.name, this.getClassLoader(), uris, this.servletContext);
return;
}
final URI uri = getConfigURI(location);
this.loggerContext = Configurator.initialize(this.name, this.getClassLoader(), uri, this.servletContext);
}
@Test
public void testBuildConfiguration() {
try {
System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
"org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory
.newConfigurationBuilder();
CustomConfigurationFactory.addTestFixtures("config name", builder);
final Configuration configuration = builder.build();
try (LoggerContext ctx = Configurator.initialize(configuration)) {
validate(configuration);
}
} finally {
System.getProperties().remove(Constants.LOG4J_CONTEXT_SELECTOR);
}
}
@Test
public void debugChangeLevelAllChildrenLoggers() {
// Use logger AND child loggers
logger.debug("Debug message 1");
loggerChild.debug("Debug message 1 child");
loggerGrandchild.debug("Debug message 1 grandchild");
assertEventCount(app.getEvents(), 3);
Configurator.setAllLevels(logger.getName(), Level.OFF);
logger.debug("Debug message 2");
loggerChild.warn("Warn message 2 child");
loggerGrandchild.fatal("Fatal message 2 grandchild");
assertEventCount(app.getEvents(), 3);
Configurator.setAllLevels(logger.getName(), Level.DEBUG);
logger.debug("Debug message 3");
loggerChild.warn("Trace message 3 child");
loggerGrandchild.trace("Fatal message 3 grandchild");
assertEventCount(app.getEvents(), 5);
}
private static void devTestBeforeClass() {
log4jLog.info("Dummy-Start-Log in beforeClass()"); // force init. of log4j (needed?? does not harm)
@SuppressWarnings("resource")
LoggerContext context = LoggerContext.getContext(false); // this matches Configurator.setLevel() impl. (instead of "LogManager.getContext();")
System.out.println("beforeClass(): LogCtx " + context + " '" + context.getName() + "', loc = " + context.getConfigLocation()
+ ", cfg = " + context.getConfiguration());
for (org.apache.logging.log4j.Logger lg : context.getLoggers()) {
System.out.println("- Logger '" + lg.getName() + "', lvl = " + lg.getLevel());
}
// force level change
System.out.println("sysout: now calling log4j-setLevel()");
Configurator.setLevel("log4jTest.Dummy_set_in_devTestBeforeClass", org.apache.logging.log4j.Level.DEBUG);
}
/**
* The main method of the application.
*
* @param args the command line arguments passed to the program.
*/
@SuppressWarnings("PMD.DoNotCallSystemExit") // Using System.exit is allowed for an actual application to exit.
public static void main(String[] args)
{
ToolsCommonConstants.ReturnValue returnValue;
try
{
// Initialize Log4J with the resource. The configuration itself can use "monitorInterval" to have it refresh if it came from a file.
LoggerContext loggerContext = Configurator.initialize(null, ToolsCommonConstants.LOG4J_CONFIG_LOCATION);
// For some initialization errors, a null context will be returned.
if (loggerContext == null)
{
// We shouldn't get here since we already checked if the location existed previously.
throw new IllegalArgumentException("Invalid configuration found at resource location: \"" + ToolsCommonConstants.LOG4J_CONFIG_LOCATION + "\".");
}
RetentionExpirationDestroyerApp exporterApp = new RetentionExpirationDestroyerApp();
returnValue = exporterApp.go(args);
}
catch (Exception e)
{
LOGGER.error("Error running herd retention expiration destroyer application. {}", e.toString(), e);
returnValue = ToolsCommonConstants.ReturnValue.FAILURE;
}
// Exit with the return code.
System.exit(returnValue.getReturnCode());
}
@Test
public void debugChangeLevelsMap() {
logger.debug("Debug message 1");
assertEventCount(app.getEvents(), 1);
final Map<String, Level> map = new HashMap<>();
map.put(logger.getName(), Level.OFF);
Configurator.setLevel(map);
logger.debug("Debug message 2");
assertEventCount(app.getEvents(), 1);
map.put(logger.getName(), Level.DEBUG);
Configurator.setLevel(map);
logger.debug("Debug message 3");
assertEventCount(app.getEvents(), 2);
}
@Test
public void debugChangeRootLevel() {
logger.debug("Debug message 1");
assertEventCount(app.getEvents(), 1);
Configurator.setRootLevel(Level.OFF);
logger.debug("Debug message 2");
assertEventCount(app.getEvents(), 1);
Configurator.setRootLevel(Level.DEBUG);
logger.debug("Debug message 3");
assertEventCount(app.getEvents(), 2);
}
@Override
public Statement apply(final Statement base, final Description description) {
// Hack: Using -DEBUG as a JVM param sets a property called "EBUG"...
if (System.getProperties().containsKey("EBUG")) {
StatusLogger.getLogger().setLevel(Level.DEBUG);
}
testClassName = description.getClassName();
return new Statement() {
@Override
public void evaluate() throws Throwable {
if (contextSelectorClass != null) {
System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, contextSelectorClass.getName());
}
// TODO Consider instead of the above:
// LogManager.setFactory(new Log4jContextFactory(LoaderUtil.newInstanceOf(contextSelectorClass)));
System.setProperty(SYS_PROP_KEY_CLASS_NAME, description.getClassName());
System.setProperty(SYS_PROP_KEY_DISPLAY_NAME, description.getDisplayName());
loggerContext = Configurator.initialize(description.getDisplayName(),
description.getTestClass().getClassLoader(), configurationLocation);
try {
base.evaluate();
} finally {
if (!Configurator.shutdown(loggerContext, shutdownTimeout, shutdownTimeUnit)) {
StatusLogger.getLogger().error("Logger context {} did not shutdown completely after {} {}.",
loggerContext.getName(), shutdownTimeout, shutdownTimeUnit);
}
loggerContext = null;
contextSelectorClass = null;
StatusLogger.getLogger().reset();
System.clearProperty(Constants.LOG4J_CONTEXT_SELECTOR);
System.clearProperty(SYS_PROP_KEY_CLASS_NAME);
System.clearProperty(SYS_PROP_KEY_DISPLAY_NAME);
}
}
};
}
@Test
public void testRememberSettings_Size() throws Exception {
//
// A place to remember settings like size and the type of view showing
//
// Enable tracing to catch odd test failure
LoggingInitialization.initializeLoggingSystem();
Logger logger = LogManager.getLogger(GhidraFileChooser.class);
Configurator.setLevel(logger.getName(), Level.TRACE);
final JComponent component = chooser.getComponent();
Dimension originalSize = component.getSize();
DockingDialog dialog = (DockingDialog) getInstanceField("dialog", chooser);
final Dimension updatedSize =
new Dimension(originalSize.width * 2, originalSize.height * 2);
runSwing(() -> dialog.setSize(updatedSize));
// close to save the changes
close();
// load the saved changes
show(false);
final AtomicReference<Dimension> preferredSizeReference = new AtomicReference<>();
runSwing(() -> {
Dimension preferredSize = chooser.getDefaultSize();
preferredSizeReference.set(preferredSize);
});
assertEquals("File chooser did not remember last picked size", updatedSize,
preferredSizeReference.get());
}
/**
* @param args
*/
public static void main(final String[] args) {
try (final LoggerContext ctx = Configurator.initialize(FormatterLoggerManualExample.class.getName(),
"target/test-classes/log4j2-console.xml");) {
final User user = new User();
logger.debug("User %s with birthday %s", user.getName(), user.getBirthdayCalendar());
logger.debug("User %1$s with birthday %2$tm %2$te, %2$tY", user.getName(), user.getBirthdayCalendar());
logger.debug("Integer.MAX_VALUE = %,d", Integer.MAX_VALUE);
logger.debug("Long.MAX_VALUE = %,d", Long.MAX_VALUE);
}
}
static void test(final String[] args, final String config) {
// System.out.println(System.getProperty("java.class.path"));
try (final LoggerContext ctx = Configurator
.initialize(ConsoleAppenderDefaultSuppressedThrowable.class.getName(), config)) {
final IOException ioEx = new IOException("test suppressed");
ioEx.addSuppressed(new IOException("test suppressed 1", new IOException("test 1")));
final IOException ioEx2 = new IOException("test 2");
ioEx2.addSuppressed(new IOException("test 3"));
ioEx.addSuppressed(new IOException("test suppressed 2", ioEx2));
final IOException e = new IOException("test", ioEx);
LOG.error("Error message {}, suppressed?", "Hi", e);
System.out.println("printStackTrace");
e.printStackTrace();
}
}
/**
* The main method of the Downloader Application.
*
* @param args the command line arguments passed to the program.
*/
@SuppressWarnings("PMD.DoNotCallSystemExit") // Using System.exit is allowed for an actual application to exit.
public static void main(String[] args)
{
ReturnValue returnValue;
try
{
// Initialize Log4J with the resource. The configuration itself can use "monitorInterval" to have it refresh if it came from a file.
LoggerContext loggerContext = Configurator.initialize(null, ToolsCommonConstants.LOG4J_CONFIG_LOCATION);
// For some initialization errors, a null context will be returned.
if (loggerContext == null)
{
// We shouldn't get here since we already checked if the location existed previously.
throw new IllegalArgumentException("Invalid configuration found at resource location: \"" + ToolsCommonConstants.LOG4J_CONFIG_LOCATION + "\".");
}
DownloaderApp downloaderApp = new DownloaderApp();
returnValue = downloaderApp.go(args);
}
catch (Exception e)
{
LOGGER.error("Error running herd downloader. {}", e.toString(), e);
returnValue = ReturnValue.FAILURE;
}
// Exit with the return code.
System.exit(returnValue.getReturnCode());
}
private LoggerContext configure(String configLocation) throws Exception {
File file = new File(configLocation);
InputStream is = new FileInputStream(file);
ConfigurationSource source = new ConfigurationSource(is, file);
LoggerContextFactory factory = org.apache.logging.log4j.LogManager.getFactory();
LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
Configuration configuration = new XmlConfigurationFactory().getConfiguration(context, source);
assertNotNull("No configuration created", configuration);
Configurator.reconfigure(configuration);
return context;
}
/**
* Tests that on calling the website twice, only the first time unauthorized response is returned.
*
* @throws Exception if an error occurs
*/
@Test
public void basicAuthentication_singleAuthenticaiton() throws Exception {
final Logger logger = (Logger) LogManager.getLogger("org.apache.http.headers");
final Level oldLevel = logger.getLevel();
Configurator.setLevel(logger.getName(), Level.DEBUG);
final StringWriter stringWriter = new StringWriter();
final PatternLayout layout = PatternLayout.newBuilder().withPattern("%msg%n").build();
final WriterAppender writerAppender = WriterAppender.newBuilder().setName("writeLogger").setTarget(stringWriter)
.setLayout(layout).build();
writerAppender.start();
logger.addAppender(writerAppender);
try {
((DefaultCredentialsProvider) getWebClient().getCredentialsProvider()).addCredentials("jetty", "jetty");
loadPage("Hi There");
int unauthorizedCount = StringUtils.countMatches(stringWriter.toString(), "HTTP/1.1 401");
assertEquals(1, unauthorizedCount);
// and again
loadPage("Hi There");
unauthorizedCount = StringUtils.countMatches(stringWriter.toString(), "HTTP/1.1 401");
assertEquals(1, unauthorizedCount);
}
finally {
logger.removeAppender(writerAppender);
Configurator.setLevel(logger.getName(), oldLevel);
}
}