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

The following examples show how to use org.apache.logging.log4j.Logger#debug() . 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: 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 3
Source File: MapFilterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfig() {
    final Configuration config = context.getConfiguration();
    final Filter filter = config.getFilter();
    assertNotNull("No MapFilter", filter);
    assertTrue("Not a MapFilter", filter instanceof  MapFilter);
    final MapFilter mapFilter = (MapFilter) filter;
    assertFalse("Should not be And filter", mapFilter.isAnd());
    final IndexedReadOnlyStringMap map = mapFilter.getStringMap();
    assertNotNull("No Map", map);
    assertFalse("No elements in Map", map.isEmpty());
    assertEquals("Incorrect number of elements in Map", 1, map.size());
    assertTrue("Map does not contain key eventId", map.containsKey("eventId"));
    assertEquals("List does not contain 2 elements", 2, map.<Collection<?>>getValue("eventId").size());
    final Logger logger = LogManager.getLogger(MapFilterTest.class);
    final Map<String, String> eventMap = new HashMap<>();
    eventMap.put("eventId", "Login");
    logger.debug(new StringMapMessage(eventMap));
    final ListAppender app = context.getListAppender("LIST");
    final List<String> msgs = app.getMessages();
    assertNotNull("No messages", msgs);
    assertFalse("No messages", msgs.isEmpty());


}
 
Example 4
Source File: YNetRunnerRepository.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void dump(Logger logger) {
    logger.debug("\n*** DUMPING {} ENTRIES IN CASE_2_NETRUNNER MAP ***", this.size());
    int sub = 1;
    for (YIdentifier key : this.keySet()) {
         if (key == null) {
             logger.debug("Key = NULL !!!");
         }
         else {
             YNetRunner runner = this.get(key);
             if (runner != null) {
                 logger.debug("Entry {} Key={}", sub++, key.get_idString());
                 logger.debug("    CaseID        {}", runner.get_caseID());
                 logger.debug("    YNetID        {}", runner.getSpecificationID().getUri());
             }
         }
    }
    logger.debug("*** DUMP OF CASE_2_NETRUNNER_MAP ENDS");
}
 
Example 5
Source File: S3Service.java    From crate with Apache License 2.0 6 votes vote down vote up
static AWSCredentialsProvider buildCredentials(Logger logger, S3ClientSettings clientSettings) {
    final AWSCredentials credentials = clientSettings.credentials;
    if (credentials == null) {
        logger.debug("Using instance profile credentials");
        var ec2ContainerCredentialsProviderWrapper = new EC2ContainerCredentialsProviderWrapper();
        try {
            // Check if credentials are available
            ec2ContainerCredentialsProviderWrapper.getCredentials();
            return ec2ContainerCredentialsProviderWrapper;
        } catch (SdkClientException e) {
            throw new InvalidArgumentException(
                "Cannot find required credentials to create a repository of type s3. " +
                "Credentials must be provided either as repository options access_key and secret_key or AWS IAM roles."
                );
        }
    } else {
        logger.debug("Using basic key/secret credentials");
        return new AWSStaticCredentialsProvider(credentials);
    }
}
 
Example 6
Source File: Log4j2MetricsTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 7
Source File: RakNetPacket.java    From JRakNet with MIT License 5 votes vote down vote up
/**
 * Maps all <code>public</code> packet IDs to their respective field names
 * and vice-versa.
 * <p>
 * Packet IDs {@link #ID_CUSTOM_0}, {@link #ID_CUSTOM_1},
 * {@link #ID_CUSTOM_2}, {@link #ID_CUSTOM_3}, {@link #ID_CUSTOM_4},
 * {@link #ID_CUSTOM_5}, {@link #ID_CUSTOM_6}, {@link #ID_CUSTOM_7},
 * {@link #ID_CUSTOM_8}, {@link #ID_CUSTOM_9}, {@link #ID_CUSTOM_A},
 * {@link #ID_CUSTOM_B}, {@link #ID_CUSTOM_C}, {@link #ID_CUSTOM_D},
 * {@link #ID_CUSTOM_E}, {@link #ID_CUSTOM_F}, {@link #ID_ACK}, and
 * {@link #ID_NACK} are ignored as they are not only internal packets but
 * they also override other packets with the same ID.
 */
private static void mapNameIds() {
	if (mappedNameIds == false) {
		Logger log = LogManager.getLogger(RakNetPacket.class);
		for (Field field : RakNetPacket.class.getFields()) {
			if (field.getType().equals(short.class)) {
				try {
					short packetId = field.getShort(null);
					if ((packetId >= ID_CUSTOM_0 && packetId <= ID_CUSTOM_F) || packetId == ID_ACK
							|| packetId == ID_NACK) {
						continue; // Ignored as they override other packet
									// IDs
					}
					String packetName = field.getName();
					String currentName = PACKET_NAMES.put(packetId, packetName);
					PACKET_IDS.put(packetName, packetId);
					if (currentName != null) {
						if (!currentName.equals(packetName)) {
							log.warn("Found duplicate ID " + RakNet.toHexStringId(packetId) + " for \"" + packetName
									+ "\" and \"" + currentName + "\", overriding name and ID");
						}
					} else {
						log.debug("Assigned packet ID " + RakNet.toHexStringId(packetId) + " to " + packetName);
					}
				} catch (ReflectiveOperationException e) {
					e.printStackTrace();
				}
			}
		}
		mappedNameIds = true;
	}
}
 
Example 8
Source File: AssemblyResultSet.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Dumps debugging information into a logger.
 *
 * @param logger where to dump the information.
 *
 * @throws NullPointerException if {@code logger} is {@code null}.
 */
public void debugDump(final Logger logger) {
    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);
    debugDump(pw);
    final String str = sw.toString();
    final String[] lines = str.split("\n");
    for (final String line : lines) {
        if (line.isEmpty()) {
            continue;
        }
        logger.debug(line);
    }
}
 
Example 9
Source File: JvmGcMonitorService.java    From crate with Apache License 2.0 5 votes vote down vote up
static void logGcOverhead(
    final Logger logger,
    final JvmMonitor.Threshold threshold,
    final long current,
    final long elapsed,
    final long seq) {
    switch (threshold) {
        case WARN:
            if (logger.isWarnEnabled()) {
                logger.warn(OVERHEAD_LOG_MESSAGE, seq, TimeValue.timeValueMillis(current), TimeValue.timeValueMillis(elapsed));
            }
            break;
        case INFO:
            if (logger.isInfoEnabled()) {
                logger.info(OVERHEAD_LOG_MESSAGE, seq, TimeValue.timeValueMillis(current), TimeValue.timeValueMillis(elapsed));
            }
            break;
        case DEBUG:
            if (logger.isDebugEnabled()) {
                logger.debug(OVERHEAD_LOG_MESSAGE, seq, TimeValue.timeValueMillis(current), TimeValue.timeValueMillis(elapsed));
            }
            break;

        default:
            break;
    }
}
 
Example 10
Source File: AssemblyResultSet.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Dumps debugging information into a logger.
 *
 * @param logger where to dump the information.
 *
 * @throws NullPointerException if {@code logger} is {@code null}.
 */
public void debugDump(final Logger logger) {
    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);
    debugDump(pw);
    final String str = sw.toString();
    final String[] lines = str.split("\n");
    for (final String line : lines) {
        if (line.isEmpty()) {
            continue;
        }
        logger.debug(line);
    }
}
 
Example 11
Source File: AwsEc2ServiceImpl.java    From crate with Apache License 2.0 5 votes vote down vote up
static AWSCredentialsProvider buildCredentials(Logger logger, Ec2ClientSettings clientSettings) {
    final AWSCredentials credentials = clientSettings.credentials;
    if (credentials == null) {
        logger.debug("Using either environment variables, system properties or instance profile credentials");
        return new DefaultAWSCredentialsProviderChain();
    } else {
        logger.debug("Using basic key/secret credentials");
        return new StaticCredentialsProvider(credentials);
    }
}
 
Example 12
Source File: XmlLoggerPropsTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithProps() {
    final ListAppender listAppender = context.getListAppender("List");
    assertNotNull("No List Appender", listAppender);

    try {
        assertThat(context.getConfiguration(), is(instanceOf(XmlConfiguration.class)));
        Logger logger = LogManager.getLogger(XmlLoggerPropsTest.class);
        logger.debug("Test with props");
        logger = LogManager.getLogger("tiny.bubbles");
        logger.debug("Test on root");
        final List<String> events = listAppender.getMessages();
        assertTrue("No events", events.size() > 0);
        assertTrue("Incorrect number of events", events.size() == 2);
        assertThat(events.get(0), allOf(
            containsString("user="),
            containsString("phrasex=****"),
            containsString("test=test"),
            containsString("test2=test2default"),
            containsString("test3=Unknown"),
            containsString("test4=test"),
            containsString("test5=test"),
            containsString("attribKey=attribValue"),
            containsString("duplicateKey=nodeValue")
        ));
        assertThat(events.get(1), allOf(
            containsString("user="),
            containsString("phrasex=****"),
            containsString("test=test"),
            containsString("test2=test2default"),
            containsString("test3=Unknown"),
            containsString("test4=test"),
            containsString("test5=test"),
            containsString("attribKey=attribValue"),
            containsString("duplicateKey=nodeValue")
        ));
    } finally {
        System.clearProperty("test");
    }
}
 
Example 13
Source File: FsService.java    From crate with Apache License 2.0 5 votes vote down vote up
private static FsInfo stats(FsProbe probe, FsInfo initialValue, Logger logger, @Nullable ClusterInfo clusterInfo) {
    try {
        return probe.stats(initialValue, clusterInfo);
    } catch (IOException e) {
        logger.debug("unexpected exception reading filesystem info", e);
        return null;
    }
}
 
Example 14
Source File: LoggerTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void getLogger_String_MessageFactoryMismatchNull() {
    final Logger testLogger =  testMessageFactoryMismatch("getLogger_String_MessageFactoryMismatchNull",
        StringFormatterMessageFactory.INSTANCE, null);
    testLogger.debug("%,d", Integer.MAX_VALUE);
    assertThat(list.strList, hasSize(1));
    assertThat(list.strList, hasItem(String.format("%,d", Integer.MAX_VALUE)));
}
 
Example 15
Source File: MixinClientConnection.java    From ViaFabric with MIT License 5 votes vote down vote up
@Redirect(
        method = "exceptionCaught",
        remap = false,
        at = @At(
                value = "INVOKE",
                target = "Lorg/apache/logging/log4j/Logger;debug(Ljava/lang/String;Ljava/lang/Throwable;)V"
        ))
private void redirectDebug(Logger logger, String message, Throwable t) {
    if ("Failed to sent packet".equals(message)) {
        logger.info(message, t);
    } else {
        logger.debug(message, t);
    }
}
 
Example 16
Source File: AbstractJpaAppenderTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testBasicJpaEntityAppender() throws SQLException {
    try {
        this.setUp("log4j2-" + this.databaseType + "-jpa-basic.xml");

        final Error exception = new Error("Goodbye, cruel world!");
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final PrintWriter writer = new PrintWriter(outputStream);
        exception.printStackTrace(writer);
        writer.close();
        final String stackTrace = outputStream.toString().replace("\r\n", "\n");

        final long millis = System.currentTimeMillis();

        final Logger logger1 = LogManager.getLogger(this.getClass().getName() + ".testBasicJpaEntityAppender");
        final Logger logger2 = LogManager.getLogger(this.getClass().getName() + ".testBasicJpaEntityAppenderAgain");
        logger1.debug("Test my debug 01.");
        logger1.warn("This is another warning 02.", exception);
        logger2.fatal("A fatal warning has been issued.");

        final Statement statement = this.connection.createStatement();
        final ResultSet resultSet = statement.executeQuery("SELECT * FROM jpaBasicLogEntry ORDER BY id");

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

        long date = resultSet.getLong("timemillis");
        assertTrue("The date should be later than pre-logging (1).", date >= millis);
        assertTrue("The date should be earlier than now (1).", date <= System.currentTimeMillis());
        assertEquals("The level column is not correct (1).", "DEBUG", resultSet.getString("level"));
        assertEquals("The logger column is not correct (1).", logger1.getName(), resultSet.getString("loggerName"));
        assertEquals("The message column is not correct (1).", "Test my debug 01.",
                resultSet.getString("message"));
        assertNull("The exception column is not correct (1).", resultSet.getString("thrown"));

        assertTrue("There should be at least two rows.", resultSet.next());

        date = resultSet.getLong("timemillis");
        assertTrue("The date should be later than pre-logging (2).", date >= millis);
        assertTrue("The date should be earlier than now (2).", date <= System.currentTimeMillis());
        assertEquals("The level column is not correct (2).", "WARN", resultSet.getString("level"));
        assertEquals("The logger column is not correct (2).", logger1.getName(), resultSet.getString("loggerName"));
        assertEquals("The message column is not correct (2).", "This is another warning 02.",
                resultSet.getString("message"));
        assertEquals("The exception column is not correct (2).", stackTrace, resultSet.getString("thrown"));

        assertTrue("There should be three rows.", resultSet.next());

        date = resultSet.getLong("timemillis");
        assertTrue("The date should be later than pre-logging (3).", date >= millis);
        assertTrue("The date should be earlier than now (3).", date <= System.currentTimeMillis());
        assertEquals("The level column is not correct (3).", "FATAL", resultSet.getString("level"));
        assertEquals("The logger column is not correct (3).", logger2.getName(), resultSet.getString("loggerName"));
        assertEquals("The message column is not correct (3).", "A fatal warning has been issued.",
                resultSet.getString("message"));
        assertNull("The exception column is not correct (3).", resultSet.getString("thrown"));

        assertFalse("There should not be four rows.", resultSet.next());
    } finally {
        this.tearDown();
    }
}
 
Example 17
Source File: KubeCluster.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the cluster named by the TEST_CLUSTER environment variable, if set, otherwise finds a cluster that's
 * both installed and running.
 * @return The cluster.
 * @throws NoClusterException If no running cluster was found.
 */
static KubeCluster bootstrap() throws NoClusterException {
    Logger logger = LogManager.getLogger(KubeCluster.class);

    KubeCluster[] clusters = null;
    String clusterName = System.getenv(ENV_VAR_TEST_CLUSTER);
    if (clusterName != null) {
        switch (clusterName.toLowerCase(Locale.ENGLISH)) {
            case "oc":
                clusters = new KubeCluster[]{new OpenShift()};
                break;
            case "minikube":
                clusters = new KubeCluster[]{new Minikube()};
                break;
            case "kubernetes":
                clusters = new KubeCluster[]{new Kubernetes()};
                break;
            case "minishift":
                clusters = new KubeCluster[]{new Minishift()};
                break;
            default:
                throw new IllegalArgumentException(ENV_VAR_TEST_CLUSTER + "=" + clusterName + " is not a supported cluster type");
        }
    }
    if (clusters == null) {
        clusters = new KubeCluster[]{new OpenShift(), new Minikube(), new Minishift()};
    }
    KubeCluster cluster = null;
    for (KubeCluster kc : clusters) {
        if (kc.isAvailable()) {
            logger.debug("Cluster {} is installed", kc);
            if (kc.isClusterUp()) {
                logger.debug("Cluster {} is running", kc);
                cluster = kc;
                break;
            } else {
                logger.debug("Cluster {} is not running", kc);
            }
        } else {
            logger.debug("Cluster {} is not installed", kc);
        }
    }
    if (cluster == null) {
        throw new NoClusterException(
                "Unable to find a cluster; tried " + Arrays.toString(clusters));
    }
    return cluster;
}
 
Example 18
Source File: BasicLoggingTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void test1() {
    final Logger logger = LogManager.getLogger(BasicLoggingTest.class.getName());
    logger.debug("debug not set");
    logger.error("Test message");
}
 
Example 19
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 20
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;
    }
}