ch.qos.logback.core.read.ListAppender Java Examples

The following examples show how to use ch.qos.logback.core.read.ListAppender. 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: AbstractVirtualHostTest.java    From qpid-broker-j with Apache License 2.0 7 votes vote down vote up
private void assertActionProducesLogMessage(final Runnable action, final String loggerName,
                                            final Level logLevel, final String message) throws Exception
{
    final CountDownLatch logMessageReceivedLatch = new CountDownLatch(1);
    ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    ListAppender<ILoggingEvent> appender = new ListAppender<>();
    appender.addFilter(new Filter<ILoggingEvent>()
    {
        @Override
        public FilterReply decide(final ILoggingEvent event)
        {
            if (event.getLoggerName().equals(loggerName) && event.getLevel().equals(logLevel) && event.getFormattedMessage().contains(message))
            {
                logMessageReceivedLatch.countDown();
            }
            return FilterReply.NEUTRAL;
        }
    });
    appender.setContext(rootLogger.getLoggerContext());
    appender.start();
    rootLogger.addAppender(appender);

    action.run();
    assertTrue("Did not receive expected log message", logMessageReceivedLatch.await(2, TimeUnit.SECONDS));
}
 
Example #2
Source File: LoggingBootstrap.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
/**
 * Prepares the logging. This method must be called before any logging occurs
 */
public static void prepareLogging() {

    final ch.qos.logback.classic.Logger logger = getRootLogger();


    final Iterator<Appender<ILoggingEvent>> iterator = logger.iteratorForAppenders();
    while (iterator.hasNext()) {
        final Appender<ILoggingEvent> next = iterator.next();
        //We remove the appender for the moment
        logger.detachAppender(next);
        defaultAppenders.add(next);
    }


    //This appender just adds entries to an Array List so we can queue the log statements for later
    listAppender = new ListAppender<>();
    listAppender.start();
    logger.addAppender(listAppender);

}
 
Example #3
Source File: PeriodicalHealthChecksTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void startShouldLogPeriodicallyWhenDegraded() {
    ListAppender<ILoggingEvent> loggingEvents = getListAppenderForClass(PeriodicalHealthChecks.class);

    TestingHealthCheck degraded = () -> Mono.just(Result.degraded(TestingHealthCheck.COMPONENT_NAME, "cause"));
    testee = new PeriodicalHealthChecks(ImmutableSet.of(degraded),
        scheduler,
        new PeriodicalHealthChecksConfiguration(PERIOD));
    testee.start();

    scheduler.advanceTimeBy(PERIOD);
    assertThat(loggingEvents.list).hasSize(1)
        .allSatisfy(loggingEvent -> {
            assertThat(loggingEvent.getLevel()).isEqualTo(Level.WARN);
            assertThat(loggingEvent.getFormattedMessage()).contains("DEGRADED", "testing", "cause");
        });
}
 
Example #4
Source File: PeriodicalHealthChecksTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void startShouldLogPeriodicallyWhenUnhealthy() {
    ListAppender<ILoggingEvent> loggingEvents = getListAppenderForClass(PeriodicalHealthChecks.class);

    TestingHealthCheck unhealthy = () -> Mono.just(Result.unhealthy(TestingHealthCheck.COMPONENT_NAME, "cause"));
    testee = new PeriodicalHealthChecks(ImmutableSet.of(unhealthy),
        scheduler,
        new PeriodicalHealthChecksConfiguration(PERIOD));
    testee.start();

    scheduler.advanceTimeBy(PERIOD);
    assertThat(loggingEvents.list).hasSize(1)
        .allSatisfy(loggingEvent -> {
            assertThat(loggingEvent.getLevel()).isEqualTo(Level.ERROR);
            assertThat(loggingEvent.getFormattedMessage()).contains("UNHEALTHY", "testing", "cause");
        });
}
 
Example #5
Source File: PeriodicalHealthChecksTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void startShouldLogWhenMultipleHealthChecks() {
    ListAppender<ILoggingEvent> loggingEvents = getListAppenderForClass(PeriodicalHealthChecks.class);

    TestingHealthCheck unhealthy = () -> Mono.just(Result.unhealthy(TestingHealthCheck.COMPONENT_NAME, "cause"));
    TestingHealthCheck degraded = () -> Mono.just(Result.degraded(TestingHealthCheck.COMPONENT_NAME, "cause"));
    TestingHealthCheck healthy = () -> Mono.just(Result.healthy(TestingHealthCheck.COMPONENT_NAME));

    testee = new PeriodicalHealthChecks(ImmutableSet.of(unhealthy, degraded, healthy),
        scheduler,
        new PeriodicalHealthChecksConfiguration(PERIOD));
    testee.start();

    scheduler.advanceTimeBy(PERIOD);

    SoftAssertions.assertSoftly(softly -> {
        softly.assertThat(loggingEvents.list).hasSize(2);
        softly.assertThat(loggingEvents.list.stream()
            .map(event -> new Tuple(event.getLevel(), event.getFormattedMessage()))
            .collect(Guavate.toImmutableList()))
            .containsExactlyInAnyOrder(
                new Tuple(Level.ERROR, "UNHEALTHY: testing : cause"),
                new Tuple(Level.WARN, "DEGRADED: testing : cause"));
    });
}
 
Example #6
Source File: ExchangeRateServiceTest.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void getAllMarketPrices_withNoExchangeRates_logs_Exception() {
    int numberOfCurrencyPairsOnExchange = 0;
    ExchangeRateProvider dummyProvider = buildDummyExchangeRateProvider(numberOfCurrencyPairsOnExchange);
    ExchangeRateService service = new ExchangeRateService(Collections.singletonList(dummyProvider));

    Map<String, Object> retrievedData = service.getAllMarketPrices();

    doSanityChecksForRetrievedDataSingleProvider(
            retrievedData, dummyProvider.getPrefix(), numberOfCurrencyPairsOnExchange);

    // No exchange rates provided by this exchange, two things should happen
    // A) the timestamp should be set to 0
    // B) an error should be logged

    // A) Check that timestamp was set to 0
    // This allows Bisq clients to eventually disregard data from this provider
    assertEquals(0L, retrievedData.get(dummyProvider.getPrefix() + "Ts"));

    // B) Check that an error is logged
    // Log msg has the format: java.lang.IllegalStateException: No exchange rate data
    // found for ExchangeName-JzfP1
    List<ILoggingEvent> logsList = ((ListAppender) exchangeRateServiceLogger.getAppender(LIST_APPENDER_NAME)).list;
    assertEquals(Level.ERROR, logsList.get(0).getLevel());
    assertTrue(logsList.get(0).getMessage().endsWith("No exchange rate data found for " + dummyProvider.getName()));
}
 
Example #7
Source File: LoggerTestHelper.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
public static void assertLoggedEvent(ListAppender appender, boolean exists, String message, String loggerName, Level level)
{
    List<ILoggingEvent> events;
    synchronized(appender)
    {
        events = new ArrayList<ILoggingEvent>(appender.list);
    }

    boolean logged = false;
    for (ILoggingEvent event: events)
    {
        if (event.getFormattedMessage().equals(message) && event.getLoggerName().equals(loggerName) && event.getLevel() == level)
        {
            logged = true;
            break;
        }
    }
    assertEquals("Event " + message + " from logger " + loggerName + " of log level " + level
            + " is " + (exists ? "not" : "") + " found", exists, logged);
}
 
Example #8
Source File: TestHttpNotificationServiceSSL.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartNotificationSucceedsNoKeystorePasswd() throws ParserConfigurationException, SAXException, IOException {
    Logger notificationServiceLogger = (Logger) LoggerFactory.getLogger(NotificationServiceManager.class);
    ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
    listAppender.start();
    notificationServiceLogger.addAppender(listAppender);

    String configFileOutput = CONFIGURATION_FILE_TEXT_NO_KEYSTORE_PASSWORD.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
    IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));

    NotificationServiceManager notificationServiceManager = new NotificationServiceManager();
    notificationServiceManager.setMaxNotificationAttempts(1);
    notificationServiceManager.loadNotificationServices(new File(tempConfigFilePath));

    List<ILoggingEvent> logsList = listAppender.list;
    boolean notificationServiceFailed = false;
    for (ILoggingEvent logMessage : logsList) {
        if (logMessage.getFormattedMessage().contains("is not valid for the following reasons")) {
            notificationServiceFailed = true;
        }
    }

    assertFalse(notificationServiceFailed);
}
 
Example #9
Source File: DatadogSecretsDoNotLeakWhenApiCalledFunctionalTest.java    From kayenta with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
  listAppender = new ListAppender<>();
  Logger mockLogger =
      (Logger) LoggerFactory.getLogger("DatadogSecretsDoNotLeakWhenApiCalledFunctionalTest");
  mockLogger.addAppender(listAppender);
  listAppender.start();

  RetrofitClientFactory retrofitClientFactory = new RetrofitClientFactory();
  retrofitClientFactory.retrofitLogLevel = "BASIC";
  retrofitClientFactory.createRetrofitLogger =
      (type) -> {
        return new Slf4jRetrofitLogger(mockLogger);
      };

  objectMapper = new ObjectMapper();
  datadogRemoteService =
      DatadogConfiguration.createDatadogRemoteService(
          retrofitClientFactory,
          objectMapper,
          new RemoteService().setBaseUrl("http://localhost:" + mockServerRule.getPort()),
          new OkHttpClient());
}
 
Example #10
Source File: TestHttpNotificationServiceSSL.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartNotificationSucceedsNoKeyPasswd() throws ParserConfigurationException, SAXException, IOException {
    Logger notificationServiceLogger = (Logger) LoggerFactory.getLogger(NotificationServiceManager.class);
    ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
    listAppender.start();
    notificationServiceLogger.addAppender(listAppender);

    String configFileOutput = CONFIGURATION_FILE_TEXT_NO_KEY_PASSWORD.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
    IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));

    NotificationServiceManager notificationServiceManager = new NotificationServiceManager();
    notificationServiceManager.setMaxNotificationAttempts(1);
    notificationServiceManager.loadNotificationServices(new File(tempConfigFilePath));

    List<ILoggingEvent> logsList = listAppender.list;
    boolean notificationServiceFailed = false;
    for (ILoggingEvent logMessage : logsList) {
        if (logMessage.getFormattedMessage().contains("is not valid for the following reasons")) {
            notificationServiceFailed = true;
        }
    }

    assertFalse(notificationServiceFailed);
}
 
Example #11
Source File: TestHttpNotificationServiceSSL.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartNotificationFailsBlankKeystorePasswdCorrectKeypasswd() throws ParserConfigurationException, SAXException, IOException {
    Logger notificationServiceLogger = (Logger) LoggerFactory.getLogger(NotificationServiceManager.class);
    ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
    listAppender.start();
    notificationServiceLogger.addAppender(listAppender);

    String configFileOutput = CONFIGURATION_FILE_TEXT_BLANK_KEYSTORE_PASSWORD.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
    IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));

    NotificationServiceManager notificationServiceManager = new NotificationServiceManager();
    notificationServiceManager.setMaxNotificationAttempts(1);
    notificationServiceManager.loadNotificationServices(new File(tempConfigFilePath));

    List<ILoggingEvent> logsList = listAppender.list;
    boolean notificationServiceFailed = false;
    for (ILoggingEvent logMessage : logsList) {
        if (logMessage.getFormattedMessage().contains("'Keystore Password' validated against '' is invalid because Keystore Password cannot be empty")) {
            notificationServiceFailed = true;
        }
    }

    assertTrue(notificationServiceFailed);
}
 
Example #12
Source File: TestHttpNotificationServiceSSL.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartNotificationFailsCorrectKeystorePasswdBlankKeypasswd() throws ParserConfigurationException, SAXException, IOException {
    Logger notificationServiceLogger = (Logger) LoggerFactory.getLogger(NotificationServiceManager.class);
    ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
    listAppender.start();
    notificationServiceLogger.addAppender(listAppender);

    String configFileOutput = CONFIGURATION_FILE_TEXT_BLANK_KEY_PASSWORD.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
    IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));

    NotificationServiceManager notificationServiceManager = new NotificationServiceManager();
    notificationServiceManager.setMaxNotificationAttempts(1);
    notificationServiceManager.loadNotificationServices(new File(tempConfigFilePath));

    List<ILoggingEvent> logsList = listAppender.list;
    boolean notificationServiceFailed = false;
    for (ILoggingEvent logMessage : logsList) {
        if (logMessage.getFormattedMessage().contains("'Key Password' validated against '' is invalid because Key Password cannot be empty")) {
            notificationServiceFailed = true;
        }
    }

    assertTrue(notificationServiceFailed);
}
 
Example #13
Source File: WildcardMapTest.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp()
{
    m_listAppender = new ListAppender<>();
    m_listAppender.start();

    Logger root = (Logger) LoggerFactory.getLogger(WildcardMap.class);
    root.addAppender(m_listAppender);

    map = new WildcardMap<>();
}
 
Example #14
Source File: QueueMessageHandlerTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void processHandlerMethodException_invocableHandlerMethodNotAvailable_errorMustBeLogged() {
	// Arrange
	StaticApplicationContext applicationContext = new StaticApplicationContext();
	applicationContext.registerSingleton("sqsListenerWithoutMessageExceptionHandler",
			SqsListenerWithoutMessageExceptionHandler.class);
	applicationContext.registerBeanDefinition("queueMessageHandler",
			getQueueMessageHandlerBeanDefinition());
	applicationContext.refresh();
	MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class);

	LoggerContext logContext = (LoggerContext) LoggerFactory.getILoggerFactory();
	ListAppender<ILoggingEvent> appender = new ListAppender<>();
	appender.start();
	Logger log = logContext.getLogger(QueueMessageHandler.class);
	log.setLevel(Level.ERROR);
	log.addAppender(appender);
	appender.setContext(log.getLoggerContext());

	// Act
	assertThatThrownBy(
			() -> messageHandler
					.handleMessage(MessageBuilder.withPayload("testContent")
							.setHeader(QueueMessageHandler.LOGICAL_RESOURCE_ID,
									"receive")
							.build())).isInstanceOf(MessagingException.class);

	// Assert
	assertThat(appender.list).hasSize(1);
}
 
Example #15
Source File: QueueMessageHandlerTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void getMappingForMethod_methodWithDeletionPolicyNeverWithoutParameterTypeAcknowledgment_warningMustBeLogged()
		throws Exception {
	// Arrange
	QueueMessageHandler queueMessageHandler = new QueueMessageHandler();
	Method receiveMethod = SqsListenerDeletionPolicyNeverNoAcknowledgment.class
			.getMethod("receive", String.class);

	LoggerContext logContext = (LoggerContext) LoggerFactory.getILoggerFactory();
	ListAppender<ILoggingEvent> appender = new ListAppender<>();
	appender.start();

	Logger log = logContext.getLogger(QueueMessageHandler.class);
	log.setLevel(Level.WARN);
	log.addAppender(appender);
	appender.setContext(log.getLoggerContext());

	// Act
	queueMessageHandler.getMappingForMethod(receiveMethod, null);

	// Assert
	ILoggingEvent loggingEvent = appender.list.get(0);

	assertThat(loggingEvent.getLevel()).isSameAs(Level.WARN);
	assertThat(loggingEvent.getMessage().contains("receive")).isTrue();
	assertThat(loggingEvent.getMessage().contains(
			"org.springframework.cloud.aws.messaging.listener.QueueMessageHandlerTest$SqsListener"
					+ "DeletionPolicyNeverNoAcknowledgment")).isTrue();
}
 
Example #16
Source File: ExchangeRateServiceTest.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@BeforeAll
static void setup() {
    // Get the logger object for logs in ExchangeRateService
    exchangeRateServiceLogger = (Logger) LoggerFactory.getLogger(ExchangeRateService.class);

    // Initiate and append a ListAppender, which allows us to programmatically inspect
    // log messages
    ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
    listAppender.setName(LIST_APPENDER_NAME);
    listAppender.start();
    exchangeRateServiceLogger.addAppender(listAppender);
}
 
Example #17
Source File: PeriodicalHealthChecksTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void startShouldNotLogWhenHealthy() {
    ListAppender<ILoggingEvent> loggingEvents = getListAppenderForClass(PeriodicalHealthChecks.class);

    TestingHealthCheck healthy = () -> Mono.just(Result.healthy(TestingHealthCheck.COMPONENT_NAME));
    testee = new PeriodicalHealthChecks(ImmutableSet.of(healthy),
        scheduler,
        new PeriodicalHealthChecksConfiguration(PERIOD));
    testee.start();

    scheduler.advanceTimeBy(PERIOD);
    assertThat(loggingEvents.list).hasSize(0);
}
 
Example #18
Source File: OfframpClientImplTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Test
public void onNext_Error() throws Exception {
  Logger OfframpClientImplLogger = (Logger) LoggerFactory.getLogger(OfframpClientImpl.class);
  ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
  listAppender.start();
  OfframpClientImplLogger.addAppender(listAppender);

  Error error = new Error("That thing was wrong");
  underTest.onNext(error);

  List<ILoggingEvent> logsList = listAppender.list;
  assertThat(logsList.get(0).getMessage(), is("That thing was wrong"));
  assertEquals(Level.ERROR, logsList.get(0).getLevel());
}
 
Example #19
Source File: TestFileSystemRepository.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testMinimalArchiveCleanupIntervalHonoredAndLogged() throws Exception {
    // We are going to construct our own repository using different properties, so
    // we need to shutdown the existing one.
    shutdown();

    Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    ListAppender<ILoggingEvent> testAppender = new ListAppender<>();
    testAppender.setName("Test");
    testAppender.start();
    root.addAppender(testAppender);
    final Map<String, String> addProps = new HashMap<>();
    addProps.put(NiFiProperties.CONTENT_ARCHIVE_CLEANUP_FREQUENCY, "1 millis");
    final NiFiProperties localProps = NiFiProperties.createBasicNiFiProperties(TestFileSystemRepository.class.getResource("/conf/nifi.properties").getFile(), addProps);
    repository = new FileSystemRepository(localProps);
    repository.initialize(new StandardResourceClaimManager());
    repository.purge();

    boolean messageFound = false;
    String message = "The value of nifi.content.repository.archive.cleanup.frequency property "
            + "is set to '1 millis' which is below the allowed minimum of 1 second (1000 milliseconds). "
            + "Minimum value of 1 sec will be used as scheduling interval for archive cleanup task.";

    // Must synchronize on testAppender, because the call to append() is synchronized and this synchronize
    // keyword guards testAppender.list. Since we are accessing testAppender.list, we must do so in a thread-safe manner.
    synchronized (testAppender) {
        for (ILoggingEvent event : testAppender.list) {
            String actualMessage = event.getFormattedMessage();
            if (actualMessage.equals(message)) {
                assertEquals(event.getLevel(), Level.WARN);
                messageFound = true;
                break;
            }
        }
    }

    assertTrue(messageFound);
}
 
Example #20
Source File: RequestContextExportingAppenderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@SafeVarargs
private final List<ILoggingEvent> prepare(Consumer<RequestContextExportingAppender>... configurators) {
    final RequestContextExportingAppender a = new RequestContextExportingAppender();
    for (Consumer<RequestContextExportingAppender> c : configurators) {
        c.accept(a);
    }

    final ListAppender<ILoggingEvent> la = new ListAppender<>();
    a.addAppender(la);
    a.start();
    la.start();
    testLogger.addAppender(a);
    return la.list;
}
 
Example #21
Source File: RequestContextExportingAppenderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testMutabilityAndImmutability() {
    final AttributeKey<Object> someAttr =
            AttributeKey.valueOf(RequestContextExportingAppenderTest.class, "SOME_ATTR");
    final RequestContextExportingAppender a = new RequestContextExportingAppender();

    // Ensure mutability before start.
    a.addBuiltIn(BuiltInProperty.ELAPSED_NANOS);
    a.addAttribute("some-attr", someAttr);
    a.addRequestHeader(HttpHeaderNames.USER_AGENT);
    a.addResponseHeader(HttpHeaderNames.SET_COOKIE);

    final ListAppender<ILoggingEvent> la = new ListAppender<>();
    a.addAppender(la);
    a.start();
    la.start();

    // Ensure immutability after start.
    assertThatThrownBy(() -> a.addBuiltIn(BuiltInProperty.REQ_PATH))
            .isExactlyInstanceOf(IllegalStateException.class);

    assertThatThrownBy(() -> a.addAttribute("my-attr", MY_ATTR))
            .isExactlyInstanceOf(IllegalStateException.class);

    assertThatThrownBy(() -> a.addRequestHeader(HttpHeaderNames.ACCEPT))
            .isExactlyInstanceOf(IllegalStateException.class);

    assertThatThrownBy(() -> a.addResponseHeader(HttpHeaderNames.DATE))
            .isExactlyInstanceOf(IllegalStateException.class);
}
 
Example #22
Source File: TestLog.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private TestLog(Function<LoggerContext, Logger> logProvider) {
    LoggerContext logCtx = (LoggerContext) LoggerFactory.getILoggerFactory();
    log = logProvider.apply(logCtx);
    list = new ListAppender<>();
    list.start();
    log.addAppender(list);
    log.setAdditive(false);
    log.setLevel(Level.WARN);
}
 
Example #23
Source File: LoggerTestHelper.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
public static ListAppender createAndRegisterAppender(String appenderName)
{
    ListAppender appender = new ListAppender();
    appender.setName(appenderName);
    ROOT_LOGGER.addAppender(appender);
    appender.start();
    return appender;
}
 
Example #24
Source File: BrokerLoggerTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception
{

    _taskExecutor = new TaskExecutorImpl();
    _taskExecutor.start();

    _loggerAppender = new ListAppender<>();
    _loggerAppender.setName(APPENDER_NAME);


    Model model = BrokerModel.getInstance();

    _broker = mock(Broker.class);
    when(_broker.getCategoryClass()).thenReturn(Broker.class);
    when(_broker.getTypeClass()).thenReturn(Broker.class);
    when(_broker.getModel()).thenReturn(model);
    when(_broker.getChildExecutor()).thenReturn(_taskExecutor);
    doReturn(Broker.class).when(_broker).getCategoryClass();

    Map<String, Object> attributes = new HashMap<>();
    attributes.put("name", APPENDER_NAME);
    _brokerLogger = new AbstractBrokerLogger(attributes, _broker)
    {
        @Override
        public Appender<ILoggingEvent> createAppenderInstance(Context context)
        {
            return _loggerAppender;
        }
    };
    _brokerLogger.open();
}
 
Example #25
Source File: LoggingTestSupport.java    From styx with Apache License 2.0 5 votes vote down vote up
private ListAppender<ILoggingEvent> addListAppender() {
    ListAppender<ILoggingEvent> appender = new ListAppender<>();
    appender.setContext((Context) LoggerFactory.getILoggerFactory());
    appender.start();

    logger.addAppender(appender);

    return appender;
}
 
Example #26
Source File: ThreadPoolTestBase.java    From sofa-common-tools with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeTest() {
    System.setProperty("logging.path", "./logs");
    System.setProperty("logging.level.com.alipay.sofa.thread", "debug");
    System.setProperty("file.encoding", "UTF-8");

    infoListAppender = new ListAppender<ILoggingEvent>();
    aberrantListAppender = new ListAppender<ILoggingEvent>();
    infoListAppender.start();
    aberrantListAppender.start();
    ((Logger) ThreadLogger.INFO_THREAD_LOGGER).addAppender(infoListAppender);
    ((Logger) ThreadLogger.WARN_THREAD_LOGGER).addAppender(aberrantListAppender);
}
 
Example #27
Source File: TestFileSystemRepository.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testMinimalArchiveCleanupIntervalHonoredAndLogged() throws Exception {
    // We are going to construct our own repository using different properties, so
    // we need to shutdown the existing one.
    shutdown();

    Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    ListAppender<ILoggingEvent> testAppender = new ListAppender<>();
    testAppender.setName("Test");
    testAppender.start();
    root.addAppender(testAppender);
    final Map<String, String> addProps = new HashMap<>();
    addProps.put(NiFiProperties.CONTENT_ARCHIVE_CLEANUP_FREQUENCY, "1 millis");
    final NiFiProperties localProps = NiFiProperties.createBasicNiFiProperties(null, addProps);
    repository = new FileSystemRepository(localProps);
    repository.initialize(new StandardResourceClaimManager());
    repository.purge();

    boolean messageFound = false;
    String message = "The value of nifi.content.repository.archive.cleanup.frequency property "
            + "is set to '1 millis' which is below the allowed minimum of 1 second (1000 milliseconds). "
            + "Minimum value of 1 sec will be used as scheduling interval for archive cleanup task.";
    for (ILoggingEvent event : testAppender.list) {
        String actualMessage = event.getFormattedMessage();
        if (actualMessage.equals(message)) {
            assertEquals(event.getLevel(), Level.WARN);
            messageFound = true;
            break;
        }
    }
    assertTrue(messageFound);
}
 
Example #28
Source File: MobiusHooksTest.java    From mobius with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  appender = new ListAppender<>();
  appender.start();

  logbackLogger = (Logger) LoggerFactory.getLogger(MobiusHooks.class);

  logbackLogger.addAppender(appender);
  MobiusHooks.setDefaultErrorHandler();
}
 
Example #29
Source File: LoggingTestSupport.java    From styx with Apache License 2.0 4 votes vote down vote up
private void removeListAppender(ListAppender<ILoggingEvent> appender) {
    logger.detachAppender(appender);
}
 
Example #30
Source File: PeriodicalHealthChecksTest.java    From james-project with Apache License 2.0 3 votes vote down vote up
public static ListAppender<ILoggingEvent> getListAppenderForClass(Class clazz) {
    Logger logger = (Logger) LoggerFactory.getLogger(clazz);

    ListAppender<ILoggingEvent> loggingEventListAppender = new ListAppender<>();
    loggingEventListAppender.start();

    logger.addAppender(loggingEventListAppender);

    return loggingEventListAppender;
}