Java Code Examples for org.apache.logging.log4j.Logger#warn()

The following examples show how to use org.apache.logging.log4j.Logger#warn() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConsoleAppenderAnsiStyleLayoutMain.java    From logging-log4j2 with Apache License 2.0 7 votes vote down vote up
public void test(final String[] args) {
    System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable
    // System.out.println(System.getProperty("java.class.path"));
    final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-style-ansi.xml"
            : args[0];
    try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) {
        final Logger logger = LogManager.getLogger(ConsoleAppenderAnsiStyleLayoutMain.class);
        logger.fatal("Fatal message.");
        logger.error("Error message.");
        logger.warn("Warning message.");
        logger.info("Information message.");
        logger.debug("Debug message.");
        logger.trace("Trace message.");
        logger.error("Error message.", new IOException("test"));
    }
}
 
Example 2
Source File: Manager.java    From signald with GNU General Public License v3.0 6 votes vote down vote up
public static List<Manager> getAll() {
    Logger logger = LogManager.getLogger("manager");
    // We have to create a manager for each account that we're listing, which is all of them :/
    List<Manager> allManagers = new LinkedList<>();
    File[] allAccounts = new File(dataPath).listFiles();
    if(allAccounts == null) {
        return allManagers;
    }
    for(File account : allAccounts) {
        if(!account.isDirectory()) {
            try {
                allManagers.add(Manager.get(account.getName()));
            } catch (IOException | NoSuchAccountException e) {
                logger.warn("Failed to load account from file: " + account.getAbsolutePath());
                e.printStackTrace();
            }
        }
    }
    return allManagers;
}
 
Example 3
Source File: CommandLineUtils.java    From besu with Apache License 2.0 6 votes vote down vote up
/**
 * Check if options are passed that require an option to be true to have any effect and log a
 * warning with the list of affected options.
 *
 * <p>Note that in future version of PicoCLI some options dependency mechanism may be implemented
 * that could replace this. See https://github.com/remkop/picocli/issues/295
 *
 * @param logger the logger instance used to log the warning
 * @param commandLine the command line containing the options we want to check
 * @param mainOptionName the name of the main option to test dependency against. Only used for
 *     display.
 * @param isMainOptionCondition the condition to test the options dependencies, if true will test
 *     if not won't
 * @param dependentOptionsNames a list of option names that can't be used if condition is met.
 *     Example: if --miner-coinbase is in the list and condition is that --miner-enabled should
 *     not be false, we log a warning.
 */
public static void checkOptionDependencies(
    final Logger logger,
    final CommandLine commandLine,
    final String mainOptionName,
    final boolean isMainOptionCondition,
    final List<String> dependentOptionsNames) {
  if (isMainOptionCondition) {
    final String affectedOptions =
        commandLine.getCommandSpec().options().stream()
            .filter(
                option ->
                    Arrays.stream(option.names()).anyMatch(dependentOptionsNames::contains)
                        && !option.stringValues().isEmpty())
            .map(option -> option.names()[0])
            .collect(
                Collectors.collectingAndThen(
                    Collectors.toList(), StringUtils.joiningWithLastDelimiter(", ", " and ")));

    if (!affectedOptions.isEmpty()) {
      logger.warn(DEPENDENCY_WARNING_MSG, affectedOptions, mainOptionName);
    }
  }
}
 
Example 4
Source File: ChatComponentParser.java    From Angelia-core with GNU General Public License v3.0 6 votes vote down vote up
private static ClickEvent parseClickEvent(JSONObject json, Logger logger) {
	String key = json.optString("action", null);
	if (key == null) {
		logger.warn("Received invalid click event with no action, ignoring it: " + json.toString());
		return null;
	}
	String value = json.optString("value", null);
	if (value == null) {
		logger.warn("Received invalid click event with no value, ignoring it: " + json.toString());
		return null;
	}
	switch (key.toLowerCase()) {
	case "open_url":
		return new ClickEvent(ClickEvent.Action.OPEN_URL, value);
	case "run_command":
		return new ClickEvent(ClickEvent.Action.RUN_COMMAND, value);
	case "suggest_command":
		return new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, value);
	case "change_page":
		return new ClickEvent(ClickEvent.Action.CHANGE_PAGE, value);
	default:
		logger.warn("Unknown key " + key + " for click event, ignoring it: " + json.toString());
		return null;
	}
}
 
Example 5
Source File: HDF5PCACoveragePoNCreationUtils.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Calculate the number of eigensamples given the user preferences and the
 * result of the log-normals SVD.
 *
 * @param requestedNumberOfEigensamples the user requested eigenvalues (empty means the user didn't specify any in particular).
 * @param numberOfCountColumns number of count columns in the original input.
 * @param logNormalizedSVD SVD results on the log-normalized counts.
 * @return always greater than 0.
 */
@VisibleForTesting
static int determineNumberOfEigensamples(final OptionalInt requestedNumberOfEigensamples, final int numberOfCountColumns, final SVD logNormalizedSVD, final Logger logger) {
    final int numberOfEigensamples;
    if (requestedNumberOfEigensamples.isPresent()) {
        if (requestedNumberOfEigensamples.getAsInt() > numberOfCountColumns) {
            logger.warn(String.format("The number of requested eigensamples (%d) is larger than the available number of read count columns after filtering (%d), thus we will have to use the latter.", requestedNumberOfEigensamples.getAsInt(), numberOfCountColumns));
        }
        numberOfEigensamples = Math.min(requestedNumberOfEigensamples.getAsInt(), numberOfCountColumns);
    } else {
        final double[] singularValues = logNormalizedSVD.getSingularValues();
        final double mean = MathUtils.mean(singularValues, 0, singularValues.length);
        final double eigenvalueCutoff = mean * JOLLIFES_RULE_MEAN_FACTOR; // Jollife's less strict version of Kaiser' Rule.
        numberOfEigensamples = (int) DoubleStream.of(singularValues).filter(v -> v > eigenvalueCutoff).count();
        logger.info(String.format("Jollife's rule produced %d eigensamples out of %d possibles for the reduced PoN", numberOfEigensamples, numberOfCountColumns));
    }
    return numberOfEigensamples;
}
 
Example 6
Source File: Scope.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
public void dumpFieldAccess(final Logger logger) {
  for (final FieldAccess fa : this.fieldAccesses) {
    if (fa.returnType == null) {
      logger.warn("missing returnType {}", fa);
    } else {
      logger.trace("# {}", fa);
    }
  }
  for (final MethodCall mc : this.methodCalls) {
    if (mc.returnType == null) {
      logger.warn("missing returnType {}", mc);
    } else {
      logger.trace("# {}", mc);
    }
  }
}
 
Example 7
Source File: XmlCompactFileAppenderValidationTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void validateXmlSchemaThrowable() throws Exception {
    final File file = new File("target", "XmlCompactFileAppenderValidationTest.log.xml");
    file.delete();
    final Logger log = LogManager.getLogger("com.foo.Bar");
    try {
        throw new IllegalArgumentException("IAE");
    } catch (final IllegalArgumentException e) {
        log.warn("Message 1", e);
    }
    Configurator.shutdown(this.loggerContext);
    this.validateXmlSchema(file);
}
 
Example 8
Source File: XmlCompactFileAppenderValidationTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void validateXmlSchema() throws Exception {
    final File file = new File("target", "XmlCompactFileAppenderValidationTest.log.xml");
    file.delete();
    final Logger log = LogManager.getLogger("com.foo.Bar");
    log.warn("Message 1");
    log.info("Message 2");
    log.debug("Message 3");
    Configurator.shutdown(this.loggerContext);
    this.validateXmlSchema(file);
}
 
Example 9
Source File: CallerInformationTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassLogger() throws Exception {
    final ListAppender app = context.getListAppender("Class").clear();
    final Logger logger = context.getLogger("ClassLogger");
    logger.info("Ignored message contents.");
    logger.warn("Verifying the caller class is still correct.");
    logger.error("Hopefully nobody breaks me!");
    final List<String> messages = app.getMessages();
    assertEquals("Incorrect number of messages.", 3, messages.size());
    for (final String message : messages) {
        assertEquals("Incorrect caller class name.", this.getClass().getName(), message);
    }
}
 
Example 10
Source File: ReverseProxyServlet.java    From logbook with MIT License 5 votes vote down vote up
@Override
protected void onProxyResponseFailure(HttpServletRequest request, HttpServletResponse response,
        Response proxyResponse,
        Throwable failure) {

    Logger logger = LogManager.getLogger(ReverseProxyServlet.class);

    logger.warn("通信に失敗しました", failure);
    logger.warn(request);
    logger.warn(proxyResponse);

    super.onProxyResponseFailure(request, response, proxyResponse, failure);
}
 
Example 11
Source File: AwsEc2ServiceImpl.java    From crate with Apache License 2.0 5 votes vote down vote up
static ClientConfiguration buildConfiguration(Logger logger, Ec2ClientSettings clientSettings) {
    final ClientConfiguration clientConfiguration = new ClientConfiguration();
    // the response metadata cache is only there for diagnostics purposes,
    // but can force objects from every response to the old generation.
    clientConfiguration.setResponseMetadataCacheSize(0);
    clientConfiguration.setProtocol(clientSettings.protocol);
    if (Strings.hasText(clientSettings.proxyHost)) {
        // TODO: remove this leniency, these settings should exist together and be validated
        clientConfiguration.setProxyHost(clientSettings.proxyHost);
        clientConfiguration.setProxyPort(clientSettings.proxyPort);
        clientConfiguration.setProxyUsername(clientSettings.proxyUsername);
        clientConfiguration.setProxyPassword(clientSettings.proxyPassword);
    }
    // Increase the number of retries in case of 5xx API responses
    final Random rand = Randomness.get();
    final RetryPolicy retryPolicy = new RetryPolicy(
        RetryPolicy.RetryCondition.NO_RETRY_CONDITION,
        (originalRequest, exception, retriesAttempted) -> {
            // with 10 retries the max delay time is 320s/320000ms (10 * 2^5 * 1 * 1000)
            logger.warn("EC2 API request failed, retry again. Reason was:", exception);
            return 1000L * (long) (10d * Math.pow(2, retriesAttempted / 2.0d) * (1.0d + rand.nextDouble()));
        },
        10,
        false);
    clientConfiguration.setRetryPolicy(retryPolicy);
    clientConfiguration.setSocketTimeout(clientSettings.readTimeoutMillis);
    return clientConfiguration;
}
 
Example 12
Source File: MelloriLogHandler.java    From vethrfolnir-mu with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void publish(LogRecord record)
{
	String loggerName = record.getLoggerName();
	if (loggerName == null)
	{
		loggerName = "";
	}
	
	Logger log = LogManager.getLogger(loggerName);
	
	org.apache.logging.log4j.Level level = levels.get(record.getLevel());
	
	if (level == null)
	{
		log.warn("Cannot find log4j level for: " + record.getLevel());
		level = org.apache.logging.log4j.Level.INFO;
	}
	
	String message = (record.getParameters() != null) && (record.getParameters().length > 0) ? MessageFormat.format(record.getMessage(), record.getParameters()) : record.getMessage();
	
	// Resource waster here
	// TODO: Finish all the logging then remove this
	String[] splits = record.getLoggerName().split("\\.");
	
	if(message.contains(splits[splits.length-1]+": "))
		message = message.replace(splits[splits.length-1]+":", "");
	
	log.log(level, message, record.getThrown());
}
 
Example 13
Source File: MergePolicyConfig.java    From crate with Apache License 2.0 5 votes vote down vote up
MergePolicyConfig(Logger logger, IndexSettings indexSettings) {
    this.logger = logger;
    final double forceMergeDeletesPctAllowed = indexSettings.getValue(INDEX_MERGE_POLICY_EXPUNGE_DELETES_ALLOWED_SETTING); // percentage
    final ByteSizeValue floorSegment = indexSettings.getValue(INDEX_MERGE_POLICY_FLOOR_SEGMENT_SETTING);
    int maxMergeAtOnce = indexSettings.getValue(INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE_SETTING);
    final int maxMergeAtOnceExplicit = indexSettings.getValue(INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE_EXPLICIT_SETTING);
    // TODO is this really a good default number for max_merge_segment, what happens for large indices, won't they end up with many segments?
    final ByteSizeValue maxMergedSegment = indexSettings.getValue(INDEX_MERGE_POLICY_MAX_MERGED_SEGMENT_SETTING);
    double segmentsPerTier = indexSettings.getValue(INDEX_MERGE_POLICY_SEGMENTS_PER_TIER_SETTING);
    double reclaimDeletesWeight = indexSettings.getValue(INDEX_MERGE_POLICY_RECLAIM_DELETES_WEIGHT_SETTING);
    final double deletesPctAllowed = indexSettings.getValue(INDEX_MERGE_POLICY_DELETES_PCT_ALLOWED_SETTING);
    this.mergesEnabled = indexSettings.getSettings().getAsBoolean(INDEX_MERGE_ENABLED, true);
    if (mergesEnabled == false) {
        logger.warn("[{}] is set to false, this should only be used in tests and can cause serious problems in production environments", INDEX_MERGE_ENABLED);
    }
    maxMergeAtOnce = adjustMaxMergeAtOnceIfNeeded(maxMergeAtOnce, segmentsPerTier);
    mergePolicy.setNoCFSRatio(indexSettings.getValue(INDEX_COMPOUND_FORMAT_SETTING));
    mergePolicy.setForceMergeDeletesPctAllowed(forceMergeDeletesPctAllowed);
    mergePolicy.setFloorSegmentMB(floorSegment.getMbFrac());
    mergePolicy.setMaxMergeAtOnce(maxMergeAtOnce);
    mergePolicy.setMaxMergeAtOnceExplicit(maxMergeAtOnceExplicit);
    mergePolicy.setMaxMergedSegmentMB(maxMergedSegment.getMbFrac());
    mergePolicy.setSegmentsPerTier(segmentsPerTier);
    mergePolicy.setDeletesPctAllowed(deletesPctAllowed);
    if (logger.isTraceEnabled()) {
        logger.trace("using [tiered] merge mergePolicy with expunge_deletes_allowed[{}], floor_segment[{}], max_merge_at_once[{}], max_merge_at_once_explicit[{}], max_merged_segment[{}], segments_per_tier[{}], deletes_pct_allowed[{}]",
            forceMergeDeletesPctAllowed, floorSegment, maxMergeAtOnce, maxMergeAtOnceExplicit, maxMergedSegment, segmentsPerTier, deletesPctAllowed);
    }
}
 
Example 14
Source File: AppService.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
public JSONObject toKAFKAOnExecution() {
    JSONObject jsonMain = new JSONObject();
    JSONObject jsonMyRequest = new JSONObject();
    JSONObject jsonMyResponse = new JSONObject();
    try {
        // Request Information.
        if (!(this.getTimeoutms() == 0)) {
            jsonMyRequest.put("TimeOutMs", this.getTimeoutms());
        }
        jsonMyRequest.put("Servers", this.getServicePath());
        if (!StringUtil.isNullOrEmpty(this.getMethod())) {
            jsonMyRequest.put("KAFKA-Method", this.getMethod());
        }
        jsonMyRequest.put("ServiceType", this.getType());
        if (!(this.getHeaderList().isEmpty())) {
            JSONObject jsonHeaders = new JSONObject();
            for (AppServiceHeader header : this.getHeaderList()) {
                if (header.getKey().contains("passw")) {
                    jsonHeaders.put(header.getKey(), "XXXXXXXX");
                } else {
                    jsonHeaders.put(header.getKey(), header.getValue());
                }
            }
            jsonMyRequest.put("KAFKA-PropsHeader", jsonHeaders);
        }
        jsonMyRequest.put("KAFKA-Request", this.getServiceRequest());
        jsonMyRequest.put("KAFKA-Key", this.getKafkaKey());
        if (!(this.getKafkaWaitNbEvent() == 0)) {
            jsonMyRequest.put("WaitNbEvents", this.getKafkaWaitNbEvent());
        }
        if (!(this.getKafkaWaitSecond() == 0)) {
            jsonMyRequest.put("WaitSeconds", this.getKafkaWaitSecond());
        }
        jsonMyRequest.put("KAFKA-FilterPath", this.getKafkaFilterPath());
        jsonMyRequest.put("KAFKA-FilterValue", this.getKafkaFilterValue());

        jsonMain.put("Request", jsonMyRequest);

        // Response Information.
        if (this.getKafkaResponseOffset() >= 0) {
            jsonMyResponse.put("Offset", this.getKafkaResponseOffset());
        }
        if (this.getKafkaResponsePartition() >= 0) {
            jsonMyResponse.put("Partition", this.getKafkaResponsePartition());
        }
        if (!StringUtil.isNullOrEmpty(this.getResponseHTTPBody())) {
            jsonMyResponse.put("Messages", this.getResponseHTTPBody());
        }
        jsonMain.put("Response", jsonMyResponse);

    } catch (JSONException ex) {
        Logger LOG = LogManager.getLogger(RecorderService.class);
        LOG.warn(ex);
    }
    return jsonMain;
}
 
Example 15
Source File: PostgresHandle.java    From okapi with Apache License 2.0 4 votes vote down vote up
PostgresHandle(Vertx vertx, JsonObject conf) {
  String val;

  connectOptions = new PgConnectOptions();
  val = Config.getSysConf("postgres_host", null, conf);
  if (val != null) {
    connectOptions.setHost(val);
  }
  val = Config.getSysConf("postgres_port", null, conf);
  Logger logger = OkapiLogger.get();
  if (val != null) {
    try {
      connectOptions.setPort(Integer.parseInt(val));
    } catch (NumberFormatException e) {
      logger.warn("Bad postgres_port value: {}: {}", val, e.getMessage());
    }
  }

  // postgres_user is supported for system configuration (-D option) only and is deprecated
  connectOptions.setUser(Config.getSysConf("postgres_username",
      Config.getSysConf("postgres_user", "okapi", new JsonObject()), conf));
  connectOptions.setPassword(Config.getSysConf("postgres_password", "okapi25", conf));
  connectOptions.setDatabase(Config.getSysConf("postgres_database", "okapi", conf));
  String serverPem = Config.getSysConf("postgres_server_pem", null, conf);
  if (serverPem != null) {
    logger.debug("Enforcing SSL encryption for PostgreSQL connections, "
        + "requiring TLSv1.3 with server name certificate");
    connectOptions.setSslMode(SslMode.VERIFY_FULL);
    connectOptions.setHostnameVerificationAlgorithm("HTTPS");
    connectOptions.setPemTrustOptions(
        new PemTrustOptions().addCertValue(Buffer.buffer(serverPem)));
    connectOptions.setEnabledSecureTransportProtocols(Collections.singleton("TLSv1.3"));
    connectOptions.setOpenSslEngineOptions(new OpenSSLEngineOptions());
  }

  PoolOptions poolOptions = new PoolOptions();
  poolOptions.setMaxSize(5);

  pool = PgPool.pool(vertx, connectOptions, poolOptions);
  logger.debug("created");
}
 
Example 16
Source File: SettingsUpdater.java    From crate with Apache License 2.0 4 votes vote down vote up
private void logUnknownSetting(final String settingType, final Map.Entry<String, String> e, final Logger logger) {
    logger.warn("ignoring existing unknown {} setting: [{}] with value [{}]; archiving", settingType, e.getKey(), e.getValue());
}
 
Example 17
Source File: TestCaseStepActionControlExecution.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Convert the current TestCaseStepActionControlExecution into JSON format
 * Note that if withChilds and withParents are both set to true, only the
 * child will be included to avoid loop.
 *
 * @param withChilds boolean that define if childs should be included
 * @param withParents boolean that define if parents should be included
 * @return TestCaseStepActionControlExecution in JSONObject format
 */
public JSONObject toJson(boolean withChilds, boolean withParents) {
    JSONObject result = new JSONObject();
    // Check if both parameter are not set to true
    if (withChilds == true && withParents == true) {
        withParents = false;
    }
    try {
        result.put("type", "testCaseStepActionControlExecution");
        result.put("id", this.getId());
        result.put("test", this.getTest());
        result.put("testcase", this.getTestCase());
        result.put("step", this.getStep());
        result.put("index", this.getIndex());
        result.put("sequence", this.getSequence());
        result.put("control", this.getControlSequence());
        result.put("sort", this.getSort());
        result.put("conditionOperator", this.getConditionOperator());
        result.put("conditionVal1Init", this.getConditionVal1Init());
        result.put("conditionVal2Init", this.getConditionVal2Init());
        result.put("conditionVal3Init", this.getConditionVal3Init());
        result.put("conditionVal1", this.getConditionVal1());
        result.put("conditionVal2", this.getConditionVal2());
        result.put("conditionVal3", this.getConditionVal3());
        result.put("controlType", this.getControl());
        result.put("controlProperty", this.getValue1());
        result.put("controlPropertyInit", this.getValue1Init());
        result.put("controlValue", this.getValue2());
        result.put("controlValueInit", this.getValue2Init());
        result.put("controlValue3", this.getValue3());
        result.put("controlValue3Init", this.getValue3Init());
        result.put("fatal", this.getFatal());
        result.put("start", this.getStart());
        result.put("end", this.getEnd());
        result.put("startlong", this.getStartLong());
        result.put("endlong", this.getEndLong());
        result.put("description", this.getDescription());
        result.put("returnCode", this.getReturnCode());
        result.put("returnMessage", this.getReturnMessage());

        if (withChilds) {
            JSONArray array = new JSONArray();
            if (this.getFileList() != null) {
                for (Object actionFileList : this.getFileList()) {
                    if (actionFileList != null) {
                        array.put(((TestCaseExecutionFile) actionFileList).toJson());
                    }
                }
            }
            result.put("fileList", array);
        }

        if (withParents) {
            result.put("testCaseStepActionExecution", this.getTestCaseStepActionExecution().toJson(false, true));
        }

    } catch (JSONException ex) {
        Logger LOG = LogManager.getLogger(TestCaseStepActionControlExecution.class);
        LOG.warn(ex);
    }
    return result;
}
 
Example 18
Source File: AzureConfiguration.java    From crate with Apache License 2.0 4 votes vote down vote up
/**
 * Check if discovery is meant to start
 *
 * @param settings settings to extract cloud enabled parameter from
 * @return true if we can start discovery features
 */
public static boolean isDiscoveryReady(Settings settings, Logger logger) {
    // Cloud services are disabled
    if (!isCloudReady(settings)) {
        logger.trace("cloud settings are disabled");
        return false;
    }

    // User set discovery.zen.hosts_provider: azure
    if (!AZURE.equalsIgnoreCase(settings.get(DiscoveryModule.DISCOVERY_SEED_PROVIDERS_SETTING.getKey()))) {
        logger.trace("{} not set to {}", DiscoveryModule.DISCOVERY_SEED_PROVIDERS_SETTING.getKey(), AZURE);
        return false;
    }

    if (isPropertyMissing(settings, Management.SUBSCRIPTION_ID.getKey()) ||
        isPropertyMissing(settings, Management.RESOURCE_GROUP_NAME.getKey()) ||
        isPropertyMissing(settings, Management.TENANT_ID.getKey()) ||
        isPropertyMissing(settings, Management.APP_ID.getKey()) ||
        isPropertyMissing(settings, Management.APP_SECRET.getKey())
        ) {
        logger.warn("one or more azure discovery settings are missing. " +
                    "Check crate.yml file. Should have [{}], [{}], [{}] and [{}].",
            Management.SUBSCRIPTION_ID,
            Management.RESOURCE_GROUP_NAME,
            Management.TENANT_ID,
            Management.APP_ID,
            Management.APP_SECRET);
        return false;
    }

    String discoveryType = AzureComputeService.Discovery.DISCOVERY_METHOD.get(settings);
    if (!(SUBNET.equalsIgnoreCase(discoveryType) ||
          VNET.equalsIgnoreCase(discoveryType) ||
          discoveryType == null)) {
        logger.warn("{} must be set to {} or {}. Ignoring value {}", AzureComputeService.Discovery.DISCOVERY_METHOD.getKey(), VNET, SUBNET, discoveryType);
    }

    logger.trace("all required properties for azure discovery are set!");

    return true;
}
 
Example 19
Source File: MemoryMappedFileAppenderRemapTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testMemMapExtendsIfNeeded() throws Exception {
    final File f = new File(LOGFILE);
    if (f.exists()) {
        assertTrue(f.delete());
    }
    assertTrue(!f.exists());

    final Logger log = LogManager.getLogger();
    final char[] text = new char[200];
    Arrays.fill(text, 'A');
    try {
        log.warn("Test log1");
        assertTrue(f.exists());
        assertEquals("initial length", 256, f.length());

        log.warn(new String(text));
        assertEquals("grown", 256 * 2, f.length());
        
        log.warn(new String(text));
        assertEquals("grown again", 256 * 3, f.length());
    } finally {
        CoreLoggerContexts.stopLoggerContext(false);
    }
    final int LINESEP = System.lineSeparator().length();
    assertEquals("Shrunk to actual used size", 658 + 3 * LINESEP, f.length());

    String line1, line2, line3, line4;
    try (final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE))) {
        line1 = reader.readLine();
        line2 = reader.readLine();
        line3 = reader.readLine();
        line4 = reader.readLine();
    }
    assertNotNull(line1);
    assertThat(line1, containsString("Test log1"));

    assertNotNull(line2);
    assertThat(line2, containsString(new String(text)));

    assertNotNull(line3);
    assertThat(line3, containsString(new String(text)));

    assertNull("only three lines were logged", line4);
}
 
Example 20
Source File: HDF5PCACoveragePoN.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Create a new PoN interface to a HDF5 file.  A version check is performed and a warning message logged if the
 * PoN version number is not up to date.
 *
 * @param file      the underlying HDF5 file.
 * @param logger    the logger to log the warning message with.
 * @throws IllegalArgumentException if {@code file} is {@code null}.
 */
public HDF5PCACoveragePoN(final HDF5File file, final Logger logger) {
    this(file);
    if (getVersion() < CURRENT_PON_VERSION) {
        logger.warn("The version of the specified PoN (" + getVersion() + ") is older than the latest version " +
                "(" + CURRENT_PON_VERSION + ").");
    }
}