@Test
 public void autoStatusListener() throws JoranException {
   System.setProperty(
       ContextInitializer.STATUS_LISTENER_CLASS, TrivialStatusListener.class.getName());
   List<StatusListener> statusListenerList =
       loggerContext.getStatusManager().getCopyOfStatusListenerList();
   assertEquals(0, statusListenerList.size());
   doAutoConfigFromSystemProperties(ClassicTestConstants.INPUT_PREFIX + "autoConfig.xml");
   statusListenerList = loggerContext.getStatusManager().getCopyOfStatusListenerList();
   assertTrue(statusListenerList.size() + " should be 1", statusListenerList.size() == 1);
   // LOGBACK-767
   TrivialStatusListener tsl = (TrivialStatusListener) statusListenerList.get(0);
   assertTrue("expecting at least one event in list", tsl.list.size() > 0);
 }
  /**
   * Initialize log level overrides from debug options.
   *
   * <p>This may only be called during bootstrapping before any custom overrides are set. Your
   * milage may vary if called while the application is running.
   *
   * @throws Exception
   */
  void initializeLogLevelOverrides() throws Exception {
    // reset current overrides
    overriddenLogLevels.clear();

    // add a note to the status manager
    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final StatusManager sm = lc.getStatusManager();
    if (sm != null) {
      sm.add(new InfoStatus("Initializing log level overrides.", this));
    }

    // apply new overrides
    try {
      final Map<String, String> options =
          BootActivator.getInstance().getService(DebugOptions.class).getOptions();
      for (final Entry<String, String> e : options.entrySet()) {
        final String loggerName = getLoggerNameForDebugOption(e.getKey());
        if (loggerName != null) {
          if ((null != e.getValue()) && !"false".equalsIgnoreCase(e.getValue())) {
            setLogLevelOverride(loggerName, "DEBUG");
          }
        }
      }
    } catch (final ServiceNotAvailableException e) {
      // no debug options available (ignore)
    }
  }
  @Test(timeout = 3000L)
  public void fallbackToSafe_FollowedByRecovery()
      throws IOException, JoranException, InterruptedException {
    String path =
        CoreTestConstants.OUTPUT_DIR_PREFIX
            + "reconfigureOnChangeConfig_fallbackToSafe-"
            + diff
            + ".xml";
    File topLevelFile = new File(path);
    writeToFile(
        topLevelFile,
        "<configuration scan=\"true\" scanPeriod=\"5 millisecond\"><root level=\"ERROR\"/></configuration> ");
    configure(topLevelFile);
    CountDownLatch changeDetectedLatch = waitForReconfigurationToBeDone(null);
    ReconfigureOnChangeTask oldRoct = getRegisteredReconfigureTask();
    assertNotNull(oldRoct);
    writeToFile(
        topLevelFile,
        "<configuration scan=\"true\" scanPeriod=\"5 millisecond\">\n"
            + "  <root></configuration>");
    changeDetectedLatch.await();
    statusChecker.assertContainsMatch(Status.WARN, FALLING_BACK_TO_SAFE_CONFIGURATION);
    statusChecker.assertContainsMatch(Status.INFO, RE_REGISTERING_PREVIOUS_SAFE_CONFIGURATION);

    loggerContext.getStatusManager().clear();

    CountDownLatch secondDoneLatch = waitForReconfigurationToBeDone(oldRoct);
    writeToFile(
        topLevelFile,
        "<configuration scan=\"true\" scanPeriod=\"5 millisecond\"><root level=\"ERROR\"/></configuration> ");
    secondDoneLatch.await();
    StatusPrinter.print(loggerContext);
    statusChecker.assertIsErrorFree();
    statusChecker.containsMatch(DETECTED_CHANGE_IN_CONFIGURATION_FILES);
  }
  @Before
  public void setUp() {
    onConsoleStatusListener.setContext(context);
    context.getStatusManager().add(onConsoleStatusListener);
    onConsoleStatusListener.start();

    asyncAppender.setContext(context);
    listAppender.setContext(context);
    listAppender.setName("list");
    listAppender.start();
  }
  public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger(MyAppWithConfigFile.class);
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

    try {
      JoranConfigurator configurator = new JoranConfigurator();
      lc.reset();
      configurator.setContext(lc);
      configurator.doConfigure(args[0]);
    } catch (JoranException je) {
      StatusPrinter.print(lc.getStatusManager());
    }
    logger.info("Entering application.");
    Bar bar = new Bar();
    bar.doIt();
    logger.info("Exiting application.");
  }
  // check for deadlocks
  @Test(timeout = 4000L)
  public void scan_LOGBACK_474() throws JoranException, IOException, InterruptedException {
    loggerContext.setName("scan_LOGBACK_474");
    File file = new File(SCAN_LOGBACK_474_FILE_AS_STR);
    // StatusListenerConfigHelper.addOnConsoleListenerInstance(loggerContext, new
    // OnConsoleStatusListener());
    configure(file);

    // ReconfigureOnChangeTask roct = waitForReconfigureOnChangeTaskToRun();

    int expectedResets = 2;
    Harness harness = new Harness(expectedResets);

    RunnableWithCounterAndDone[] runnableArray = buildRunnableArray(file, UpdateType.TOUCH);
    harness.execute(runnableArray);

    loggerContext.getStatusManager().add(new InfoStatus("end of execution ", this));
    StatusPrinter.print(loggerContext);
    checkResetCount(expectedResets);
  }
  void setLogLevelOverride(final String loggerName, final String level) throws Exception {
    // get logger
    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final StatusManager sm = lc.getStatusManager();
    final Logger logger = lc.getLogger(loggerName);

    // get levels
    final Level currentLevel = logger.getLevel();
    final Level newLevel = Level.toLevel(level, null);

    if (newLevel == null) {
      // reset any current override
      final String[] removed = overriddenLogLevels.remove(loggerName);
      if (removed != null) {
        final Level toRestore = Level.toLevel(removed[1], null);
        if (sm != null) {
          sm.add(
              new InfoStatus(
                  String.format(
                      "Resetting level for logger '%s'.", loggerName, logger.getEffectiveLevel()),
                  this));
        }
        logger.setLevel(toRestore);
      }
    } else if (newLevel != currentLevel) {
      // apply new override
      overriddenLogLevels.put(
          loggerName, new String[] {level, null != currentLevel ? currentLevel.levelStr : null});
      if (sm != null) {
        sm.add(
            new InfoStatus(
                String.format("Overriding level for logger '%s' to '%s'.", loggerName, newLevel),
                this));
      }
      logger.setLevel(newLevel);
    }
  }
Пример #8
0
  public static void main(String[] args) {
    Logger logger = (Logger) LoggerFactory.getLogger(JMSTopicAppenderTestApp.class);
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    lc.reset();

    JMSTopicAppender appender = new JMSTopicAppender();
    appender.setContext(lc);
    appender.setName("jmsTopic");
    appender.setInitialContextFactoryName("org.apache.activemq.jndi.ActiveMQInitialContextFactory");
    // appender.setPassword("");
    appender.setProviderURL("tcp://localhost:61616");
    // appender.setSecurityCredentials("");
    // appender.setSecurityPrincipalName("");
    appender.setTopicBindingName("MyTopic");
    appender.setTopicConnectionFactoryBindingName("ConnectionFactory");
    // appender.setURLPkgPrefixes("");
    // appender.setUserName("");

    appender.start();
    logger.addAppender(appender);

    // JIT
    for (int i = 0; i < 10000; i++) {
      logger.debug("** Hello world. n=" + i);
    }

    long before = System.nanoTime();
    for (int i = 0; i < 10000; i++) {
      logger.debug("** Hello world. n=" + i);
    }
    long after = System.nanoTime();

    System.out.println("Time per logs for 10'000 logs: " + (after - before) / 10000);

    StatusPrinter.print(lc.getStatusManager());
  }
 void addInfo(String msg, Object o) {
   loggerContext.getStatusManager().add(new InfoStatus(msg, o));
 }