Java Code Examples for org.apache.log4j.LogManager#getLogger()

The following examples show how to use org.apache.log4j.LogManager#getLogger() . 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: MapRewriteAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testRewrite() throws Exception {
    Logger logger = LogManager.getLogger("test");
    Map<String, String> map = new HashMap<>();
    map.put("message", "This is a test");
    map.put("hello", "world");
    logger.debug(map);
    LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
    Configuration configuration = context.getConfiguration();
    Map<String, Appender> appenders = configuration.getAppenders();
    ListAppender eventAppender = null;
    for (Map.Entry<String, Appender> entry : appenders.entrySet()) {
        if (entry.getKey().equals("events")) {
            eventAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
        }
    }
    assertNotNull("No Event Appender", eventAppender);
    List<LoggingEvent> events = eventAppender.getEvents();
    assertTrue("No events", events != null && events.size() > 0);
    assertNotNull("No properties in the event", events.get(0).getProperties());
    assertTrue("Key was not inserted", events.get(0).getProperties().containsKey("hello"));
    assertEquals("Key value is incorrect", "world", events.get(0).getProperties().get("hello"));
}
 
Example 2
Source File: TaskErrorIntegrationTest.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomizedTaskFrameworkFailureInTaskCreation() throws Exception {
  TestAppender testAppender = new TestAppender();
  Logger logger = LogManager.getLogger(GobblinMultiTaskAttempt.class.getName() + "-noattempt");
  logger.addAppender(testAppender);

  Properties jobProperties =
      GobblinLocalJobLauncherUtils.getJobProperties("runtime_test/skip_workunits_test.properties");
  jobProperties.setProperty(ConfigurationKeys.SOURCE_CLASS_KEY, CustomizedTaskTestSource.class.getName());
  // To demonstrate failure caught in task creation in test setting, disabled retry in task creation.
  jobProperties.setProperty(RETRY_TIMES, "1");
  jobProperties.setProperty(RETRY_TYPE, RetryerFactory.RetryType.FIXED_ATTEMPT.name());

  try {
    GobblinLocalJobLauncherUtils.invokeLocalJobLauncher(jobProperties);
  } catch (Throwable t){
    // Expect to get exception, do nothing
  }
  Assert.assertTrue(testAppender.events.stream().anyMatch(e -> e.getRenderedMessage().contains("Could not create task for workunit")));
  logger.removeAppender(testAppender);
}
 
Example 3
Source File: AutoConfigTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testListAppender() {
    Logger logger = LogManager.getLogger("test");
    logger.debug("This is a test of the root logger");
    LoggerContext loggerContext = org.apache.logging.log4j.LogManager.getContext(false);
    Configuration configuration = ((org.apache.logging.log4j.core.LoggerContext) loggerContext).getConfiguration();
    Map<String, Appender> appenders = configuration.getAppenders();
    ListAppender eventAppender = null;
    ListAppender messageAppender = null;
    for (Map.Entry<String, Appender> entry : appenders.entrySet()) {
        if (entry.getKey().equals("list")) {
            messageAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
        } else if (entry.getKey().equals("events")) {
            eventAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
        }
    }
    assertNotNull("No Event Appender", eventAppender);
    assertNotNull("No Message Appender", messageAppender);
    List<LoggingEvent> events = eventAppender.getEvents();
    assertTrue("No events", events != null && events.size() > 0);
    List<String> messages = messageAppender.getMessages();
    assertTrue("No messages", messages != null && messages.size() > 0);
}
 
Example 4
Source File: RewriteAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testRewrite() throws Exception {
    Logger logger = LogManager.getLogger("test");
    ThreadContext.put("key1", "This is a test");
    ThreadContext.put("hello", "world");
    logger.debug("Say hello");
    LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
    Configuration configuration = context.getConfiguration();
    Map<String, Appender> appenders = configuration.getAppenders();
    ListAppender eventAppender = null;
    for (Map.Entry<String, Appender> entry : appenders.entrySet()) {
        if (entry.getKey().equals("events")) {
            eventAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
        }
    }
    assertNotNull("No Event Appender", eventAppender);
    List<LoggingEvent> events = eventAppender.getEvents();
    assertTrue("No events", events != null && events.size() > 0);
    assertNotNull("No properties in the event", events.get(0).getProperties());
    assertTrue("Key was not inserted", events.get(0).getProperties().containsKey("key2"));
    assertEquals("Key value is incorrect", "Log4j", events.get(0).getProperties().get("key2"));
}
 
Example 5
Source File: OperationREST.java    From open-Autoscaler with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/log/{level}")
public Response setLogLevel( @PathParam("level") final String level, @QueryParam("package") final String packageName) {

	String targetLoggerName = "org.cloudfoundry.autoscaler";
	
	if (packageName != null &&  !packageName.isEmpty())
		targetLoggerName = packageName; 
	
	Logger targetLogger = LogManager.getLogger(targetLoggerName);
	
	if (level.equalsIgnoreCase("INFO"))
		targetLogger.setLevel(Level.INFO);
	else if (level.equalsIgnoreCase("DEBUG"))
		targetLogger.setLevel(Level.DEBUG);
	else if (level.equalsIgnoreCase("ERROR"))
		targetLogger.setLevel(Level.ERROR);
	else if (level.equalsIgnoreCase("WARN"))
		targetLogger.setLevel(Level.WARN);
	else if (level.equalsIgnoreCase("FATAL"))
		targetLogger.setLevel(Level.FATAL);
	else if (level.equalsIgnoreCase("TRACE"))
		targetLogger.setLevel(Level.TRACE);
	else if (level.equalsIgnoreCase("OFF"))
		targetLogger.setLevel(Level.OFF);
	else if (level.equalsIgnoreCase("ALL"))
		targetLogger.setLevel(Level.ALL);
	
	logger.info("Log level " + level.toUpperCase() + " is set");
	return RestApiResponseHandler.getResponseOk();        
    
}
 
Example 6
Source File: TaskErrorIntegrationTest.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Test that a task submission error results in a log message from {@link GobblinMultiTaskAttempt}
 * and does not hang
 * @throws Exception
 */
@Test
@BMRule(name = "testErrorDuringSubmission", targetClass = "org.apache.gobblin.runtime.TaskExecutor",
    targetMethod = "submit(Task)", targetLocation = "AT ENTRY", condition = "true",
    action = "throw new RuntimeException(\"Exception for testErrorDuringSubmission\")")
public void testErrorDuringSubmission()
    throws Exception {
  TestAppender testAppender = new TestAppender();
  Logger logger = LogManager.getLogger(GobblinMultiTaskAttempt.class.getName() + "-noattempt");
  logger.addAppender(testAppender);

  Properties jobProperties =
      GobblinLocalJobLauncherUtils.getJobProperties("runtime_test/skip_workunits_test.properties");

  jobProperties.setProperty(ConfigurationKeys.SOURCE_CLASS_KEY, BaseTestSource.class.getName());
  jobProperties.setProperty(TestExtractor.RAISE_ERROR, "false");

  try {
    GobblinLocalJobLauncherUtils.invokeLocalJobLauncher(jobProperties);
  } catch (Exception e){
    // Expect to get exception, do nothing
  }

  Assert.assertTrue(testAppender.events.stream().anyMatch(e -> e.getRenderedMessage()
      .startsWith("Could not submit task for workunit")));

  logger.removeAppender(testAppender);
}
 
Example 7
Source File: TestLog4jAppender.java    From kite with Apache License 2.0 5 votes vote down vote up
@Test
public void testLog4jAppender() throws IOException {
  PropertyConfigurator.configure(props);
  Logger logger = LogManager.getLogger(TestLog4jAppender.class);
  for(int count = 0; count <= 1000; count++){
    /*
     * Log4j internally defines levels as multiples of 10000. So if we
     * create levels directly using count, the level will be set as the
     * default.
     */
    int level = ((count % 5)+1)*10000;
    String msg = "This is log message number" + String.valueOf(count);

    logger.log(Level.toLevel(level), msg);
    Transaction transaction = ch.getTransaction();
    transaction.begin();
    Event event = ch.take();
    Assert.assertNotNull(event);
    Assert.assertEquals(new String(event.getBody(), "UTF8"), msg);

    Map<String, String> hdrs = event.getHeaders();

    Assert.assertNotNull(hdrs.get(Log4jAvroHeaders.TIMESTAMP.toString()));

    Assert.assertEquals(Level.toLevel(level),
        Level.toLevel(Integer.valueOf(hdrs.get(Log4jAvroHeaders.LOG_LEVEL
            .toString()))
        ));

    Assert.assertEquals(logger.getName(),
        hdrs.get(Log4jAvroHeaders.LOGGER_NAME.toString()));

    Assert.assertEquals("UTF8",
        hdrs.get(Log4jAvroHeaders.MESSAGE_ENCODING.toString()));
    transaction.commit();
    transaction.close();
  }

}
 
Example 8
Source File: TestLog4jAppenderWithAvro.java    From kite with Apache License 2.0 5 votes vote down vote up
@Test
public void testAvroReflect() throws IOException {
  loadProperties("flume-log4jtest-avro-reflect.properties");
  PropertyConfigurator.configure(props);
  Logger logger = LogManager.getLogger(TestLog4jAppenderWithAvro.class);
  String msg = "This is log message number " + String.valueOf(0);

  AppEvent appEvent = new AppEvent();
  appEvent.setMessage(msg);

  logger.info(appEvent);

  Transaction transaction = ch.getTransaction();
  transaction.begin();
  Event event = ch.take();
  Assert.assertNotNull(event);

  Schema schema = ReflectData.get().getSchema(appEvent.getClass());

  ReflectDatumReader<AppEvent> reader = new ReflectDatumReader<AppEvent>(AppEvent.class);
  BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(event.getBody(), null);
  AppEvent recordFromEvent = reader.read(null, decoder);
  Assert.assertEquals(msg, recordFromEvent.getMessage());

  Map<String, String> hdrs = event.getHeaders();

  Assert.assertNull(hdrs.get(Log4jAvroHeaders.MESSAGE_ENCODING.toString()));

  Assert.assertNull("Schema URL should not be set",
      hdrs.get(Log4jAvroHeaders.AVRO_SCHEMA_URL.toString()));
  Assert.assertEquals("Schema string should be set", schema.toString(),
      hdrs.get(Log4jAvroHeaders.AVRO_SCHEMA_LITERAL.toString()));

  transaction.commit();
  transaction.close();

}
 
Example 9
Source File: TestLog4jAppender.java    From mt-flume with Apache License 2.0 5 votes vote down vote up
@Test(expected = EventDeliveryException.class)
public void testLog4jAppenderFailureNotUnsafeMode() throws Throwable {
  configureSource();
  PropertyConfigurator.configure(props);
  Logger logger = LogManager.getLogger(TestLog4jAppender.class);
  source.stop();
  sendAndAssertFail(logger);

}
 
Example 10
Source File: TestLog4jAppender.java    From mt-flume with Apache License 2.0 5 votes vote down vote up
@Test
public void testLog4jAppenderFailureUnsafeMode() throws Throwable {
  configureSource();
  props.setProperty("log4j.appender.out2.UnsafeMode", String.valueOf(true));
  PropertyConfigurator.configure(props);
  Logger logger = LogManager.getLogger(TestLog4jAppender.class);
  source.stop();
  sendAndAssertFail(logger);

}
 
Example 11
Source File: TestLog4jAppender.java    From kite with Apache License 2.0 4 votes vote down vote up
@Test
public void testLayout() throws IOException {
  props.put("log4j.appender.out2.layout", "org.apache.log4j.PatternLayout");
  props.put("log4j.appender.out2.layout.ConversionPattern",
      "%-5p [%t]: %m%n");
  PropertyConfigurator.configure(props);
  Logger logger = LogManager.getLogger(TestLog4jAppender.class);
  Thread.currentThread().setName("Log4jAppenderTest");
  for(int count = 0; count <= 100; count++){
    /*
     * Log4j internally defines levels as multiples of 10000. So if we
     * create levels directly using count, the level will be set as the
     * default.
     */
    int level = ((count % 5)+1)*10000;
    String msg = "This is log message number" + String.valueOf(count);

    logger.log(Level.toLevel(level), msg);
    Transaction transaction = ch.getTransaction();
    transaction.begin();
    Event event = ch.take();
    Assert.assertNotNull(event);
    StringBuilder builder = new StringBuilder();
    builder.append("[").append("Log4jAppenderTest").append("]: ")
        .append(msg);
    //INFO seems to insert an extra space, so lets split the string.
    String eventBody = new String(event.getBody(), "UTF-8");
    String eventLevel = eventBody.split("\\s+")[0];
    Assert.assertEquals(Level.toLevel(level).toString(), eventLevel);
    Assert.assertEquals(
        new String(event.getBody(), "UTF8").trim()
            .substring(eventLevel.length()).trim(), builder.toString());

    Map<String, String> hdrs = event.getHeaders();

    Assert.assertNotNull(hdrs.get(Log4jAvroHeaders.TIMESTAMP.toString()));

    Assert.assertEquals(Level.toLevel(level),
        Level.toLevel(Integer.parseInt(hdrs.get(Log4jAvroHeaders.LOG_LEVEL
            .toString()))));

    Assert.assertEquals(logger.getName(),
        hdrs.get(Log4jAvroHeaders.LOGGER_NAME.toString()));

    Assert.assertEquals("UTF8",
        hdrs.get(Log4jAvroHeaders.MESSAGE_ENCODING.toString()));
    transaction.commit();
    transaction.close();
  }


}
 
Example 12
Source File: Log4jLoggerAdapter.java    From dubbox-hystrix with Apache License 2.0 4 votes vote down vote up
public Logger getLogger(String key) {
	return new Log4jLogger(LogManager.getLogger(key));
}
 
Example 13
Source File: Log4jLoggerAdapter.java    From light-task-scheduler with Apache License 2.0 4 votes vote down vote up
public Logger getLogger(String key) {
	return new Log4jLogger(LogManager.getLogger(key));
}
 
Example 14
Source File: AdminService.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
public org.apache.log4j.Logger getLogger(String name) {
  return LogManager.getLogger(name);
}
 
Example 15
Source File: Log4jLoggerAdapter.java    From tddl5 with Apache License 2.0 4 votes vote down vote up
public Logger getLogger(String key) {
    return new Log4jLogger(LogManager.getLogger(key));
}
 
Example 16
Source File: Log4jLoggerAdapter.java    From tddl with Apache License 2.0 4 votes vote down vote up
public Logger getLogger(String key) {
    return new Log4jLogger(LogManager.getLogger(key));
}
 
Example 17
Source File: MithraTestAbstract.java    From reladomo with Apache License 2.0 4 votes vote down vote up
public org.apache.log4j.Logger getSqlLogger(Class c)
{
    String name = c.getName();
    return LogManager.getLogger("com.gs.fw.common.mithra.sqllogs." + name.substring(name.lastIndexOf('.') + 1));
}
 
Example 18
Source File: MTGLogger.java    From MtgDesktopCompanion with GNU General Public License v3.0 4 votes vote down vote up
public static Logger getLogger(Class<?> c) {
	return LogManager.getLogger(c.getName());
}
 
Example 19
Source File: Log4jLoggerAdapter.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
@Override
public Logger getLogger(String key) {
    return new Log4jLogger(LogManager.getLogger(key));
}
 
Example 20
Source File: ClientTest.java    From spinach with Apache License 2.0 4 votes vote down vote up
@Override
public void openConnection() throws Exception {
    Logger logger = LogManager.getLogger(CommandHandler.class);
    logger.setLevel(Level.ALL);
    super.openConnection();
}