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

The following examples show how to use org.apache.logging.log4j.Logger#info() . 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: PlottingUtils.java    From gatk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static Map<String, Integer> getContigLengthMap(final SAMSequenceDictionary sequenceDictionary,
                                               final int minContigLength,
                                               final Logger logger) {
    Utils.nonNull(sequenceDictionary);
    ParamUtils.isPositiveOrZero(minContigLength, "Minimum contig length must be non-negative.");
    Utils.nonNull(logger);
    Utils.validateArg(sequenceDictionary.getSequences().stream().map(SAMSequenceRecord::getSequenceName).noneMatch(n -> n.contains(CONTIG_DELIMITER)),
            String.format("Contig names cannot contain \"%s\".", CONTIG_DELIMITER));
    final Map<String, Integer> contigLengthMap = sequenceDictionary.getSequences().stream()
            .filter(s -> s.getSequenceLength() >= minContigLength)
            .collect(Collectors.toMap(SAMSequenceRecord::getSequenceName, SAMSequenceRecord::getSequenceLength,
                    (c, l) -> {
                        throw new IllegalArgumentException(String.format("Duplicate contig in sequence dictionary: %s", c));
                    },
                    LinkedHashMap::new));
    Utils.validateArg(contigLengthMap.size() > 0,
            "There must be at least one contig above the threshold length in the sequence dictionary.");
    logger.info("Contigs above length threshold: " + contigLengthMap.toString());
    return contigLengthMap;
}
 
Example 2
Source File: AsyncLoggerConfigErrorOnFormat.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testError() throws Exception {
    final File file = new File("target", "AsyncLoggerConfigErrorOnFormat.log");
    assertTrue("Deleted old file before test", !file.exists() || file.delete());

    final Logger log = LogManager.getLogger("com.foo.Bar");
    log.info(new ThrowsErrorOnFormatMessage());
    log.info("Second message");
    CoreLoggerContexts.stopLoggerContext(file); // stop async thread

    final BufferedReader reader = new BufferedReader(new FileReader(file));
    final String line1 = reader.readLine();
    final String line2 = reader.readLine();
    reader.close();
    file.delete();

    assertThat(line1, containsString("Second message"));
    assertNull("Expected only one line", line2);
}
 
Example 3
Source File: ForwardLogHandler.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void publish(LogRecord record) {
    Logger logger = getLogger(String.valueOf(record.getLoggerName())); // See SPIGOT-1230
    Throwable exception = record.getThrown();
    Level level = record.getLevel();
    String message = getFormatter().formatMessage(record);

    if (level == Level.SEVERE) {
        logger.error(message, exception);
    } else if (level == Level.WARNING) {
        logger.warn(message, exception);
    } else if (level == Level.INFO) {
        logger.info(message, exception);
    } else if (level == Level.CONFIG) {
        logger.debug(message, exception);
    } else {
        logger.trace(message, exception);
    }
}
 
Example 4
Source File: SvDiscoverFromLocalAssemblyContigAlignmentsSpark.java    From gatk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * First parse the input alignments, then classify the assembly contigs based on their alignment signatures,
 * and return the contigs that are classified together for downstream inference.
 */
public static AssemblyContigsClassifiedByAlignmentSignatures preprocess(final SvDiscoveryInputMetaData svDiscoveryInputMetaData,
                                                                        final JavaRDD<GATKRead> assemblyRawAlignments) {

    final Broadcast<SAMFileHeader> headerBroadcast = svDiscoveryInputMetaData.getSampleSpecificData().getHeaderBroadcast();
    final Broadcast<Set<String>> canonicalChromosomesBroadcast = svDiscoveryInputMetaData.getReferenceData().getCanonicalChromosomesBroadcast();
    final Logger toolLogger = svDiscoveryInputMetaData.getToolLogger();

    final JavaRDD<AssemblyContigWithFineTunedAlignments> contigsWithChimericAlignmentsReconstructed =
            AssemblyContigAlignmentsConfigPicker
                    .createOptimalCoverageAlignmentSetsForContigs(assemblyRawAlignments, headerBroadcast.getValue(),
                            canonicalChromosomesBroadcast.getValue(), 0.0, toolLogger)
                    .cache();
    toolLogger.info( contigsWithChimericAlignmentsReconstructed.count() +
            " contigs with chimeric alignments potentially giving SV signals.");

    return new AssemblyContigsClassifiedByAlignmentSignatures(contigsWithChimericAlignmentsReconstructed);
}
 
Example 5
Source File: QueueFullAsyncLoggerConfigTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
static void asyncLoggerConfigTest(final Logger logger,
                                  final Unlocker unlocker,
                                  final BlockingAppender blockingAppender) {
    for (int i = 0; i < 130; i++) {
        TRACE("Test logging message " + i  + ". Remaining capacity=" + asyncRemainingCapacity(logger));
        TRACE("Test decrementing unlocker countdown latch. Count=" + unlocker.countDownLatch.getCount());
        unlocker.countDownLatch.countDown();
        final String param = "I'm innocent";
        logger.info(new ParameterizedMessage("logging innocent object #{} {}", i, param));
    }
    TRACE("Before stop() blockingAppender.logEvents.count=" + blockingAppender.logEvents.size());
    //CoreLoggerContexts.stopLoggerContext(false); // stop async thread
    while (blockingAppender.logEvents.size() < 130) { Thread.yield(); }
    TRACE("After  stop() blockingAppender.logEvents.count=" + blockingAppender.logEvents.size());

    final Stack<String> actual = transform(blockingAppender.logEvents);
    for (int i = 0; i < 130; i++) {
        assertEquals("logging innocent object #" + i + " I'm innocent", actual.pop());
    }
    assertTrue(actual.isEmpty());
}
 
Example 6
Source File: HDF5PCACoveragePoNCreationUtils.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * SVD and Pseudo inverse calculation.
 *
 * @param logNormalized the input counts for the SVD and reduction steps, fully normalized and already logged.
 * @param requestedNumberOfEigensamples user requested number of eigensamples for the reduced panel.
 * @return never {@code null}.
 */
@VisibleForTesting
static ReductionResult calculateReducedPanelAndPInverses(final ReadCountCollection logNormalized,
                                                         final OptionalInt requestedNumberOfEigensamples,
                                                         final Logger logger,
                                                         final JavaSparkContext ctx) {

    if (ctx == null) {
        logger.warn("No Spark context provided, not going to use Spark...");
    }

    final RealMatrix logNormalizedCounts = logNormalized.counts();
    final int numberOfCountColumns = logNormalizedCounts.getColumnDimension();

    logger.info("Starting the SVD decomposition of the log-normalized counts ...");
    final long svdStartTime = System.currentTimeMillis();
    final SVD logNormalizedSVD = SVDFactory.createSVD(logNormalized.counts(), ctx);
    final long svdEndTime = System.currentTimeMillis();
    logger.info(String.format("Finished the SVD decomposition of the log-normal counts. Elapse of %d seconds", (svdEndTime - svdStartTime) / 1000));

    final int numberOfEigensamples = determineNumberOfEigensamples(requestedNumberOfEigensamples, numberOfCountColumns, logNormalizedSVD, logger);
    logger.info(String.format("Including %d eigensamples in the reduced PoN", numberOfEigensamples));

    final double[] singularValues = logNormalizedSVD.getSingularValues();
    final RealMatrix reducedCounts = logNormalizedSVD.getU().getSubMatrix(0, logNormalizedCounts.getRowDimension()-1, 0, numberOfEigensamples - 1).copy();
    reducedCounts.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() {
        @Override
        public double visit(final int row, final int column, final double value) { return singularValues[column]*value; }
    });

    // The Pseudo inverse comes nearly for free from having run the SVD decomposition.
    final RealMatrix logNormalizedPseudoInverse = logNormalizedSVD.getPinv();

    logger.info("Calculating the reduced PoN inverse matrix...");
    final long riStartTime = System.currentTimeMillis();
    final RealMatrix reducedCountsPseudoInverse = SVDFactory.createSVD(reducedCounts, ctx).getPinv();
    final long riEndTime = System.currentTimeMillis();
    logger.info(String.format("Finished calculating the reduced PoN inverse matrix. Elapse of %d seconds", (riEndTime - riStartTime) / 1000));
    return new ReductionResult(logNormalizedPseudoInverse, reducedCounts, reducedCountsPseudoInverse, logNormalizedSVD.getSingularValues());
}
 
Example 7
Source File: ContextMapLookupTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Demonstrates the use of ThreadContext in determining what log file name to use in a unit test.
 * Inspired by LOG4J2-786. Note that this only works because the ThreadContext is prepared
 * <em>before</em> the Logger instance is obtained. This use of ThreadContext and the associated
 * ContextMapLookup can be used in many other ways in a config file.
 */
@Test
public void testFileLog() throws Exception {
    final Logger logger = LogManager.getLogger();
    logger.info("Hello from testFileLog!");
    final File logFile = new File("target", this.getClass().getName() + ".testFileLog.log");
    assertTrue(logFile.exists());
}
 
Example 8
Source File: AuthenticationHandler.java    From Angelia-core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Attempts to refresh the current access token. Note that even though a token
 * might no longer be valid, it may still be possible to refresh it
 *
 * @param logger Logger used
 * @throws IOException      In case of connection problems
 * @throws Auth403Exception In case the auth server rejects, likely due to rate
 *                          limiting
 */
private void refreshToken(Logger logger) throws IOException, Auth403Exception {
	String result;
	result = sendPost(constructRefreshJSON(accessToken, playerUUID, playerName, clientToken),
			authServerAdress + "/refresh", logger);
	JSONObject jsonResult = new JSONObject(result);
	accessToken = jsonResult.getString("accessToken");
	String receivedClientToken = jsonResult.getString("clientToken");
	if (!clientToken.equals(receivedClientToken)) {
		throw new IOException("Received different client token during access token refresh");
	}
	logger.info("Successfully refreshed access token for " + playerName);
	this.lastRefresh = System.currentTimeMillis();
	sessionManager.updateAuth(this);
}
 
Example 9
Source File: log4j2Test.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
@Test
public void testLog4j2() throws InterruptedException, MQClientException {
    clear();
    Logger logger = LogManager.getLogger("test");
    for (int i = 0; i < 10; i++) {
        logger.info("log4j2 log message " + i);
    }
    int received = consumeMessages(10, "log4j2", 10);
    Assert.assertTrue(received > 5);
}
 
Example 10
Source File: log4j2Test.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 5 votes vote down vote up
@Test
public void testLog4j2() throws InterruptedException, MQClientException {
    Logger logger = LogManager.getLogger("test");
    for (int i = 0; i < 50; i++) {
        logger.info("log4j2 log message " + i);
    }
    int received = consumeMessages(30, "log4j2",30);
    Assert.assertTrue(received>20);
}
 
Example 11
Source File: ReadCountCollectionUtils.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Removes targets that are flagged for more than {@code toleratedFlagsPerSample} times per sample according to
 * a provided {@code flagger} predicate.
 *
 * If some targets are dropped, the order of the remaining targets will be the same as the original read
 * count collection.
 *
 * If no target is dropped, the original read count collection will be returned by reference.
 *
 * @param readCounts the input read counts
 * @param entryFlagger a predicate for flagging an arbitrary {@link ReadCountCollection.EntryIndex} in the read count collection
 * @param toleratedFlagsPerSample maximum tolerated flags per sample before dropping a target
 * @param reasonForFlagging a description of the reason for flagging (used for logging)
 * @param logger an instance of {@link Logger}
 * @return never {@code null}. It might be a reference to the input read-counts if there is
 *   is no target to be dropped.
 */
public static ReadCountCollection removeTargetsWithTooManyFlags(@Nonnull final ReadCountCollection readCounts,
                                                                @Nonnull final Predicate<ReadCountCollection.EntryIndex> entryFlagger,
                                                                final int toleratedFlagsPerSample,
                                                                @Nonnull final String reasonForFlagging,
                                                                @Nonnull final Logger logger) {
    Utils.nonNull(readCounts, "The input read counts must be non-null");
    Utils.nonNull(entryFlagger, "The predicate must be non-null");
    Utils.nonNull(reasonForFlagging, "The reason for flagging must be non-null");
    Utils.nonNull(logger, "The logger must be non-null");
    ParamUtils.isPositiveOrZero(toleratedFlagsPerSample, "Tolerated flags per sample must be >= 0");
    final int numTargets = readCounts.counts().getRowDimension();
    final int numColumns = readCounts.counts().getColumnDimension();
    final List<Target> originalTargets = readCounts.targets();
    final Set<Target> targetsToKeep = IntStream.range(0, numTargets)
            .filter(targetIndex -> IntStream.range(0, numColumns)
                    .filter(columnIndex -> entryFlagger.test(new ReadCountCollection.EntryIndex(targetIndex, columnIndex)))
                    .count() <= toleratedFlagsPerSample)
            .mapToObj(originalTargets::get)
            .collect(Collectors.toCollection(LinkedHashSet::new));
    final int targetsToDropCount = originalTargets.size() - targetsToKeep.size();
    if (targetsToDropCount == 0) {
        logger.info(String.format("There are no targets flagged more than %d times across all %d samples as being %s. Keeping all" +
                " %d targets.", toleratedFlagsPerSample, numColumns, reasonForFlagging, numTargets));
        return readCounts;
    } else if (targetsToDropCount == originalTargets.size()) {
        throw new UserException.BadInput(String.format("All targets are flagged more than %d times across all %d samples as being %s" +
                " resulting in all targets being dropped", toleratedFlagsPerSample, numColumns, reasonForFlagging));
    } else {
        final double droppedPercentage = ((double)(targetsToDropCount) / originalTargets.size()) * 100;
        logger.info(String.format("Some targets dropped (%d out of %d, %.2f%%) as they were flagged more than %d" +
                " times across %d samples as being %s.", targetsToDropCount, numTargets, droppedPercentage, toleratedFlagsPerSample,
                numColumns, reasonForFlagging));
        return readCounts.subsetTargets(targetsToKeep);
    }
}
 
Example 12
Source File: MongoDb4AuthFailureTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    final Logger logger = LogManager.getLogger();
    logger.info("Hello log");
    try (final MongoClient mongoClient = mongoDbTestRule.getMongoClient()) {
        final MongoDatabase database = mongoClient.getDatabase("testDb");
        Assert.assertNotNull(database);
        final MongoCollection<Document> collection = database.getCollection("testCollection");
        Assert.assertNotNull(collection);
        final Document first = collection.find().first();
        Assert.assertNull(first);
    }
}
 
Example 13
Source File: JdbcAppenderMapMessageDataSourceTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDataSourceConfig() throws Exception {
    try (final Connection connection = jdbcRule.getConnectionSource().getConnection()) {
        final Error exception = new Error("Final error massage is fatal!");
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final PrintWriter writer = new PrintWriter(outputStream);
        exception.printStackTrace(writer);
        writer.close();

        final Logger logger = LogManager.getLogger(this.getClass().getName() + ".testDataSourceConfig");
        MapMessage mapMessage = new MapMessage();
        mapMessage.with("Id", 1);
        mapMessage.with("ColumnA", "ValueA");
        mapMessage.with("ColumnB", "ValueB");
        logger.info(mapMessage);

        try (final Statement statement = connection.createStatement();
                final ResultSet resultSet = statement
                        .executeQuery("SELECT Id, ColumnA, ColumnB FROM dsLogEntry ORDER BY Id")) {

            assertTrue("There should be at least one row.", resultSet.next());

            Assert.assertEquals(1, resultSet.getInt("Id"));

            assertFalse("There should not be two rows.", resultSet.next());
        }
    }
}
 
Example 14
Source File: GameJoinHandler.java    From Angelia-core with GNU General Public License v3.0 5 votes vote down vote up
public void parseGameJoin(Logger logger, String serverAddress) throws IOException, Auth403Exception {
	while (true) {
		ReadOnlyPacket gameJoinPacket;
		try {
			gameJoinPacket = connection.getPacket();
		} catch (MalformedCompressedDataException e) {
			throw new IOException("Compression of login success packet was invalid");
		}
		if (gameJoinPacket.getPacketID() == 3) {
			handleCompressionPacket(gameJoinPacket);
		} else if (gameJoinPacket.getPacketID() == 2) {
			handleLoginSuccess(gameJoinPacket);
			return;
		} else if(gameJoinPacket.getPacketID() == 1) {
			// figure out encryption secret
			logger.info("Parsing encryption request from " + serverAddress);
			EncryptionHandler asyncEncHandler = new EncryptionHandler(connection);
			if (!asyncEncHandler.parseEncryptionRequest(gameJoinPacket)) {
				logger.info("Failed to handle encryption request, could not setup connection");
				connection.close(DisconnectReason.Unknown_Connection_Error);
				return;
			}
			asyncEncHandler.genSecretKey();
			logger.info("Authenticating connection attempt to " + serverAddress + " against Yggdrassil session server");
			connection.getAuthHandler().authAgainstSessionServer(asyncEncHandler.generateKeyHash(), logger);
			logger.info("Sending encryption reply to " + serverAddress);
			asyncEncHandler.sendEncryptionResponse();
			// everything from here on is encrypted
			logger.info("Enabling sync encryption with " + serverAddress);
			connection.setEncryptionEnabled(true);
			connection.setSyncEncryptionHandler(new AES_CFB8_Encrypter(asyncEncHandler.getSharedSecret(),
					asyncEncHandler.getSharedSecret()));
		} else if (gameJoinPacket.getPacketID() == 0) {
			handleDisconnectPacket(gameJoinPacket);
			return;
		} else
			throw new IOException("Received invalid packet with id " + gameJoinPacket.getPacketID()
					+ " while waiting for login success");
	}
}
 
Example 15
Source File: FlumePersistentAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingle() throws IOException {

    final Logger logger = LogManager.getLogger("EventLogger");
    final Marker marker = MarkerManager.getMarker("EVENT");
    logger.info(marker, "This is a test message");

    final Event event = primary.poll();
    Assert.assertNotNull(event);
    final String body = getBody(event);
    Assert.assertTrue("Channel contained event, but not expected message. Received: " + body,
        body.endsWith("This is a test message"));
}
 
Example 16
Source File: ReadCountCollectionUtils.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Remove columns that have too many counts equal to 0.
 * <p>
 *     It will return a copy of the input read-count collection with such columns dropped.
 * </p>
 *
 * @param readCounts the input read counts.
 * @param maximumColumnZeros maximum number of counts equal to 0 per column tolerated.
 * @return never {@code null}. It might be a reference to the input read-counts if there is
 *   is no column to be dropped.
 */
@VisibleForTesting
public static ReadCountCollection removeColumnsWithTooManyZeros(final ReadCountCollection readCounts,
                                                                final int maximumColumnZeros,
                                                                final boolean roundToInteger,
                                                                final Logger logger) {

    final RealMatrix counts = readCounts.counts();

    final Set<String> columnsToKeep = IntStream.range(0, counts.getColumnDimension()).boxed()
            .filter(i -> countZeroes(counts.getColumn(i), roundToInteger) <= maximumColumnZeros)
            .map(i -> readCounts.columnNames().get(i))
            .collect(Collectors.toCollection(LinkedHashSet::new));

    final int columnsToDropCount = readCounts.columnNames().size() - columnsToKeep.size();
    if (columnsToDropCount == 0) {
        logger.info(
                String.format("There were no columns with a large number of targets with zero counts " +
                        "(<= %d of %d) to drop", maximumColumnZeros, readCounts.targets().size()));
        return readCounts;
    } else if (columnsToDropCount == readCounts.columnNames().size()) {
        throw new UserException.BadInput("The number of zeros per count column is too large resulting in all count " +
                "columns to be dropped");
    } else {
        final double droppedPercentage = ((double)(columnsToDropCount) / readCounts.columnNames().size()) * 100;
        logger.info(String.format("Some counts columns dropped (%d out of %d, %.2f%%) as they had too many targets with zeros (> %d of %d)",
                columnsToDropCount, readCounts.columnNames().size(), droppedPercentage, maximumColumnZeros,
                readCounts.targets().size()));
        return readCounts.subsetColumns(columnsToKeep);
    }
}
 
Example 17
Source File: Log4JTest.java    From CrazyAlpha with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String... args) {
    Logger logger = LogManager.getLogger(Log4JTest.class);
    logger.debug("hello world");
    logger.error("hello world");
    logger.info("hello");
}
 
Example 18
Source File: JvmGcMonitorService.java    From crate with Apache License 2.0 4 votes vote down vote up
static void logSlowGc(
    final Logger logger,
    final JvmMonitor.Threshold threshold,
    final long seq,
    final JvmMonitor.SlowGcEvent slowGcEvent,
    BiFunction<JvmStats, JvmStats, String> pools) {

    final String name = slowGcEvent.currentGc.getName();
    final long elapsed = slowGcEvent.elapsed;
    final long totalGcCollectionCount = slowGcEvent.currentGc.getCollectionCount();
    final long currentGcCollectionCount = slowGcEvent.collectionCount;
    final TimeValue totalGcCollectionTime = slowGcEvent.currentGc.getCollectionTime();
    final TimeValue currentGcCollectionTime = slowGcEvent.collectionTime;
    final JvmStats lastJvmStats = slowGcEvent.lastJvmStats;
    final JvmStats currentJvmStats = slowGcEvent.currentJvmStats;
    final ByteSizeValue maxHeapUsed = slowGcEvent.maxHeapUsed;

    switch (threshold) {
        case WARN:
            if (logger.isWarnEnabled()) {
                logger.warn(
                    SLOW_GC_LOG_MESSAGE,
                    name,
                    seq,
                    totalGcCollectionCount,
                    currentGcCollectionTime,
                    currentGcCollectionCount,
                    TimeValue.timeValueMillis(elapsed),
                    currentGcCollectionTime,
                    totalGcCollectionTime,
                    lastJvmStats.getMem().getHeapUsed(),
                    currentJvmStats.getMem().getHeapUsed(),
                    maxHeapUsed,
                    pools.apply(lastJvmStats, currentJvmStats));
            }
            break;
        case INFO:
            if (logger.isInfoEnabled()) {
                logger.info(
                    SLOW_GC_LOG_MESSAGE,
                    name,
                    seq,
                    totalGcCollectionCount,
                    currentGcCollectionTime,
                    currentGcCollectionCount,
                    TimeValue.timeValueMillis(elapsed),
                    currentGcCollectionTime,
                    totalGcCollectionTime,
                    lastJvmStats.getMem().getHeapUsed(),
                    currentJvmStats.getMem().getHeapUsed(),
                    maxHeapUsed,
                    pools.apply(lastJvmStats, currentJvmStats));
            }
            break;
        case DEBUG:
            if (logger.isDebugEnabled()) {
                logger.debug(
                    SLOW_GC_LOG_MESSAGE,
                    name,
                    seq,
                    totalGcCollectionCount,
                    currentGcCollectionTime,
                    currentGcCollectionCount,
                    TimeValue.timeValueMillis(elapsed),
                    currentGcCollectionTime,
                    totalGcCollectionTime,
                    lastJvmStats.getMem().getHeapUsed(),
                    currentJvmStats.getMem().getHeapUsed(),
                    maxHeapUsed,
                    pools.apply(lastJvmStats, currentJvmStats));
            }
            break;

        default:
            break;
    }
}
 
Example 19
Source File: ClientUtil.java    From anomaly-detection with Apache License 2.0 4 votes vote down vote up
/**
 * Helper function to handle ListTasksResponse
 * @param listTasksResponse ListTasksResponse
 * @param detectorId Anomaly Detector Id
 * @param LOG Logger
 */
private void onListTaskResponse(ListTasksResponse listTasksResponse, String detectorId, Logger LOG) {
    List<TaskInfo> tasks = listTasksResponse.getTasks();
    TaskId matchedParentTaskId = null;
    TaskId matchedSingleTaskId = null;
    for (TaskInfo task : tasks) {
        if (!task.getHeaders().isEmpty()
            && task.getHeaders().get(Task.X_OPAQUE_ID).equals(CommonName.ANOMALY_DETECTOR + ":" + detectorId)) {
            if (!task.getParentTaskId().equals(TaskId.EMPTY_TASK_ID)) {
                // we found the parent task, don't need to check more
                matchedParentTaskId = task.getParentTaskId();
                break;
            } else {
                // we found one task, keep checking other tasks
                matchedSingleTaskId = task.getTaskId();
            }
        }
    }
    // case 1: given detectorId is not in current task list
    if (matchedParentTaskId == null && matchedSingleTaskId == null) {
        // log and then clear negative cache
        LOG.info("Couldn't find task for detectorId: {}. Clean this entry from Throttler", detectorId);
        throttler.clearFilteredQuery(detectorId);
        return;
    }
    // case 2: we can find the task for given detectorId
    CancelTasksRequest cancelTaskRequest = new CancelTasksRequest();
    if (matchedParentTaskId != null) {
        cancelTaskRequest.setParentTaskId(matchedParentTaskId);
        LOG.info("Start to cancel task for parentTaskId: {}", matchedParentTaskId.toString());
    } else {
        cancelTaskRequest.setTaskId(matchedSingleTaskId);
        LOG.info("Start to cancel task for taskId: {}", matchedSingleTaskId.toString());
    }

    client
        .execute(
            CancelTasksAction.INSTANCE,
            cancelTaskRequest,
            ActionListener.wrap(response -> { onCancelTaskResponse(response, detectorId, LOG); }, exception -> {
                LOG.error("Failed to cancel task for detectorId: " + detectorId, exception);
                throw new InternalFailure(detectorId, "Failed to cancel current tasks", exception);
            })
        );
}
 
Example 20
Source File: ElasticsearchAppenderTest.java    From log4j2-elasticsearch with Apache License 2.0 4 votes vote down vote up
@Test
public void testTimeLog() {
    Logger logger = LogManager.getLogger("time");
    logger.info("Hello World");
}