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

The following examples show how to use org.apache.logging.log4j.core.Logger#setLevel() . 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: AbstractADTest.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
/**
 * Set up test with junit that a warning was logged with log4j
 */
protected void setUpLog4jForJUnit(Class<?> cls) {
    String loggerName = toLoggerName(callerClass(cls));
    logger = (Logger) LogManager.getLogger(loggerName);
    testAppender = new TestAppender(loggerName);
    testAppender.start();
    logger.addAppender(testAppender);
    logger.setLevel(Level.DEBUG);
}
 
Example 2
Source File: LoggingStrategyFunctionalTest.java    From pocket-etl with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    logger = (Logger) LogManager.getRootLogger();
    appender = OutputStreamAppender.newBuilder().setName("Appender").setTarget(out).build();
    appender.start();
    logger.addAppender(appender);
    logger.setLevel(Level.INFO);
}
 
Example 3
Source File: Log4j2Test.java    From flogger with Apache License 2.0 5 votes vote down vote up
@Before
public void setUpLoggerBackend() {
  // A unique name should produce a different logger for each test allowing tests to be run in
  // parallel.
  String loggerName = String.format("%s_%02d", Log4j2Test.class.getName(), uid.incrementAndGet());
  logger = (Logger) LogManager.getLogger(loggerName);
  appender = new CapturingAppender();
  logger.addAppender(appender);
  logger.setLevel(TRACE);
  backend = new Log4j2LoggerBackend(logger);
  events = appender.events;
}
 
Example 4
Source File: LogUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public static void configureLogLevel(String logLevel) {

        Level level = Level.toLevel(logLevel);
        try {
            final Logger logger = (Logger) LogManager.getRootLogger();
            logger.setLevel(level);
        } catch (Throwable t) {
            //We catch throwable as there is a case where logger level setting fails when old SLF4j library interferes.
            log.error("Could not set the log level to : " + level + ". Probably inconsistent Log4J class is loaded.",
                    t);
        }
    }
 
Example 5
Source File: CsvParameterLayoutTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
static void testLayoutNormalApi(final Logger root, final AbstractCsvLayout layout, final boolean messageApi)
        throws Exception {
    removeAppenders(root);
    // set up appender
    final ListAppender appender = new ListAppender("List", null, layout, true, false);
    appender.start();

    appender.countDownLatch = new CountDownLatch(4);

    // set appender on root and set level to debug
    root.addAppender(appender);
    root.setLevel(Level.DEBUG);

    // output messages
    if (messageApi) {
        logDebugObjectArrayMessage(root);
    } else {
        logDebugNormalApi(root);
    }
    final int msgCount = 4;
    if (appender.getMessages().size() < msgCount) {
        // wait until background thread finished processing
        appender.countDownLatch.await(10, TimeUnit.SECONDS);
    }
    assertEquals("Background thread did not finish processing: msg count", msgCount, appender.getMessages().size());

    // don't stop appender until background thread is done
    appender.stop();

    final List<String> list = appender.getMessages();
    final char d = layout.getFormat().getDelimiter();
    Assert.assertEquals("1" + d + "2" + d + "3", list.get(0));
    Assert.assertEquals("2" + d + "3", list.get(1));
    Assert.assertEquals("5" + d + "6", list.get(2));
    Assert.assertEquals("7" + d + "8" + d + "9" + d + "10", list.get(3));
}
 
Example 6
Source File: FlumeAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testStructured() throws IOException {
    final Agent[] agents = new Agent[] { Agent.createAgent("localhost",
            testPort) };
    final FlumeAppender avroAppender = FlumeAppender.createAppender(agents,
            null, null, "false", "Avro", null, "1000", "1000", "1", "1000",
            "avro", "false", null, null, null, "ReqCtx_", null, "true",
            "1", null, null, null, null);
    avroAppender.start();
    final Logger eventLogger = (Logger) LogManager.getLogger("EventLogger");
    Assert.assertNotNull(eventLogger);
    eventLogger.addAppender(avroAppender);
    eventLogger.setLevel(Level.ALL);

    final StructuredDataMessage msg = new StructuredDataMessage("Transfer",
            "Success", "Audit");
    msg.put("memo", "This is a memo");
    msg.put("acct", "12345");
    msg.put("amount", "100.00");
    ThreadContext.put("id", UUID.randomUUID().toString());
    ThreadContext.put("memo", null);
    ThreadContext.put("test", "123");

    EventLogger.logEvent(msg);

    final Transaction transaction = channel.getTransaction();
    transaction.begin();

    final Event event = channel.take();
    Assert.assertNotNull(event);
    Assert.assertTrue("Channel contained event, but not expected message", getBody(event).endsWith("Success"));
    transaction.commit();
    transaction.close();

    eventSource.stop();
    eventLogger.removeAppender(avroAppender);
    avroAppender.stop();
}
 
Example 7
Source File: TestAppender.java    From iaf with Apache License 2.0 4 votes vote down vote up
public static void addToRootLogger(TestAppender appender, Level level) {
	Logger logger = getRootLogger();
	logger.setLevel(level);
	logger.addAppender(appender);
}
 
Example 8
Source File: SmtpAppenderTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testDelivery() {
    final String subjectKey = getClass().getName();
    final String subjectValue = "SubjectValue1";
    ThreadContext.put(subjectKey, subjectValue);
    final int smtpPort = AvailablePortFinder.getNextAvailable();
    final SmtpAppender appender = SmtpAppender.newBuilder()
            .setName("Test")
            .setTo("[email protected]")
            .setCc("[email protected]")
            .setBcc("[email protected]")
            .setFrom("[email protected]")
            .setReplyTo("[email protected]")
            .setSubject("Subject Pattern %X{" + subjectKey + "}")
            .setSmtpHost(HOST)
            .setSmtpPort(smtpPort)
            .setBufferSize(3)
            .build();
    appender.start();

    final LoggerContext context = LoggerContext.getContext();
    final Logger root = context.getLogger("SMTPAppenderTest");
    root.addAppender(appender);
    root.setAdditive(false);
    root.setLevel(Level.DEBUG);

    final SimpleSmtpServer server = SimpleSmtpServer.start(smtpPort);

    root.debug("Debug message #1");
    root.debug("Debug message #2");
    root.debug("Debug message #3");
    root.debug("Debug message #4");
    root.error("Error with exception", new RuntimeException("Exception message"));
    root.error("Error message #2");

    server.stop();
    assertTrue(server.getReceivedEmailSize() == 2);
    final Iterator<SmtpMessage> messages = server.getReceivedEmail();
    final SmtpMessage email = messages.next();

    assertEquals("[email protected]", email.getHeaderValue("To"));
    assertEquals("[email protected]", email.getHeaderValue("Cc"));
    // assertEquals("[email protected]", email.getHeaderValue("Bcc")); // BCC
    // can't be tested with Dumpster 1.6
    assertEquals("[email protected]", email.getHeaderValue("From"));
    assertEquals("[email protected]", email.getHeaderValue("Reply-To"));
    final String headerValue = email.getHeaderValue("Subject");
    assertEquals(headerValue, "Subject Pattern " + subjectValue);

    final String body = email.getBody();
    assertFalse(body.contains("Debug message #1"));
    assertTrue(body.contains("Debug message #2"));
    assertTrue(body.contains("Debug message #3"));
    assertTrue(body.contains("Debug message #4"));
    assertTrue(body.contains("Error with exception"));
    assertTrue(body.contains("RuntimeException"));
    assertTrue(body.contains("Exception message"));
    assertFalse(body.contains("Error message #2"));

    final SmtpMessage email2 = messages.next();
    final String body2 = email2.getBody();
    assertFalse(body2.contains("Debug message #4"));
    assertFalse(body2.contains("Error with exception"));
    assertTrue(body2.contains("Error message #2"));
}
 
Example 9
Source File: SocketAppenderTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
static void testTcpAppender(final TcpSocketTestServer tcpTestServer, final Logger logger, final int bufferSize)
        throws Exception {
    // @formatter:off
    final SocketAppender appender = SocketAppender.newBuilder()
            .setHost("localhost")
            .setPort(tcpTestServer.getLocalPort())
            .setReconnectDelayMillis(-1)
            .setName("test")
            .setImmediateFail(false)
            .setBufferSize(bufferSize)
            .setLayout(JsonLayout.newBuilder().setProperties(true).build())
            .build();
    // @formatter:on
    appender.start();
    Assert.assertEquals(bufferSize, appender.getManager().getByteBuffer().capacity());

    // set appender on root and set level to debug
    logger.addAppender(appender);
    logger.setAdditive(false);
    logger.setLevel(Level.DEBUG);
    final String tcKey = "UUID";
    final String expectedUuidStr = UUID.randomUUID().toString();
    ThreadContext.put(tcKey, expectedUuidStr);
    ThreadContext.push(expectedUuidStr);
    final String expectedExMsg = "This is a test";
    try {
        logger.debug("This is a test message");
        final Throwable child = new LoggingException(expectedExMsg);
        logger.error("Throwing an exception", child);
        logger.debug("This is another test message");
    } finally {
        ThreadContext.remove(tcKey);
        ThreadContext.pop();
    }
    Thread.sleep(250);
    LogEvent event = tcpTestServer.getQueue().poll(3, TimeUnit.SECONDS);
    assertNotNull("No event retrieved", event);
    assertTrue("Incorrect event", event.getMessage().getFormattedMessage().equals("This is a test message"));
    assertTrue("Message not delivered via TCP", tcpTestServer.getCount() > 0);
    assertEquals(expectedUuidStr, event.getContextData().getValue(tcKey));
    event = tcpTestServer.getQueue().poll(3, TimeUnit.SECONDS);
    assertNotNull("No event retrieved", event);
    assertTrue("Incorrect event", event.getMessage().getFormattedMessage().equals("Throwing an exception"));
    assertTrue("Message not delivered via TCP", tcpTestServer.getCount() > 1);
    assertEquals(expectedUuidStr, event.getContextStack().pop());
    assertNotNull(event.getThrownProxy());
    assertEquals(expectedExMsg, event.getThrownProxy().getMessage());
}