Java Code Examples for java.util.logging.LogManager#getLogManager()

The following examples show how to use java.util.logging.LogManager#getLogManager() . 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: LoggingDeadlock.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException{
    Thread t1 = new Thread(new Runnable() {
        public void run() {
            randomDelay();
            // Trigger Logger.<clinit>
            Logger.getAnonymousLogger();
        }
    });

    Thread t2 = new Thread(new Runnable() {
        public void run() {
            randomDelay();
            // Trigger LogManager.<clinit>
            LogManager.getLogManager();
        }
    });

    t1.start();
    t2.start();

    t1.join();
    t2.join();
    System.out.println("\nTest passed");
}
 
Example 2
Source File: ThreadLogFormatter.java    From reef with Apache License 2.0 6 votes vote down vote up
public ThreadLogFormatter() {

    super();
    final LogManager logManager = LogManager.getLogManager();
    final String className = this.getClass().getName();

    final String format = logManager.getProperty(className + ".format");
    this.logFormat = format != null ? format : DEFAULT_FORMAT;

    final String rawDropStr = logManager.getProperty(className + ".dropPrefix");
    if (rawDropStr != null) {
      for (String prefix : rawDropStr.trim().split(",")) {
        prefix = prefix.trim();
        if (!prefix.isEmpty()) {
          this.dropPrefix.add(prefix);
        }
      }
    }
  }
 
Example 3
Source File: HttpConnection.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
public HttpConnection(String requestMethod,
                      URL url,
                      String contentType) {
    this.requestMethod = requestMethod;
    this.url = url;
    this.contentType = contentType;
    this.requestProperties = new HashMap<String, String>();
    this.requestInterceptors = new LinkedList<HttpConnectionRequestInterceptor>();
    this.responseInterceptors = new LinkedList<HttpConnectionResponseInterceptor>();

    // Calculate log filter for this request if logging is enabled
    if (logger.isLoggable(Level.FINE)) {
        LogManager m = LogManager.getLogManager();
        String httpMethodFilter = m.getProperty("com.cloudant.http.filter.method");
        String urlFilter = m.getProperty("com.cloudant.http.filter.url");
        if (httpMethodFilter != null) {
            // Split the comma separated list of methods
            List<String> methods = Arrays.asList(httpMethodFilter.split(","));
            requestIsLoggable = requestIsLoggable && methods.contains(requestMethod);
        }
        if (urlFilter != null) {
            requestIsLoggable = requestIsLoggable && url.toString().matches(urlFilter);
        }
    }
}
 
Example 4
Source File: LoggingDeadlock.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException{
    Thread t1 = new Thread(new Runnable() {
        public void run() {
            randomDelay();
            // Trigger Logger.<clinit>
            Logger.getAnonymousLogger();
        }
    });

    Thread t2 = new Thread(new Runnable() {
        public void run() {
            randomDelay();
            // Trigger LogManager.<clinit>
            LogManager.getLogManager();
        }
    });

    t1.start();
    t2.start();

    t1.join();
    t2.join();
    System.out.println("\nTest passed");
}
 
Example 5
Source File: LoggingDeadlock.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException{
    Thread t1 = new Thread(new Runnable() {
        public void run() {
            randomDelay();
            // Trigger Logger.<clinit>
            Logger.getAnonymousLogger();
        }
    });

    Thread t2 = new Thread(new Runnable() {
        public void run() {
            randomDelay();
            // Trigger LogManager.<clinit>
            LogManager.getLogManager();
        }
    });

    t1.start();
    t2.start();

    t1.join();
    t2.join();
    System.out.println("\nTest passed");
}
 
Example 6
Source File: DataflowWorkerHarnessHelper.java    From beam with Apache License 2.0 5 votes vote down vote up
public static void initializeLogging(Class<?> workerHarnessClass) {
  /* Set up exception handling tied to the workerHarnessClass. */
  Thread.setDefaultUncaughtExceptionHandler(
      new WorkerUncaughtExceptionHandler(LoggerFactory.getLogger(workerHarnessClass)));

  // Reset the global log manager, get the root logger and remove the default log handlers.
  LogManager logManager = LogManager.getLogManager();
  logManager.reset();
  java.util.logging.Logger rootLogger = logManager.getLogger(ROOT_LOGGER_NAME);
  for (Handler handler : rootLogger.getHandlers()) {
    rootLogger.removeHandler(handler);
  }
  DataflowWorkerLoggingInitializer.initialize();
}
 
Example 7
Source File: L4MLogger.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Default initialization, checking for applet in sandbox.
 */
protected void initialize() {
	String loggerName = getName();
	boolean runningSandbox = false;
	// check if we are running in an applet sandbox
	SecurityManager sm = System.getSecurityManager();
	if (null != sm) {
		try {
			Permission perm = new java.util.logging.LoggingPermission("control", "");
			sm.checkPermission(perm);
		} catch (SecurityException e) {
			System.out.println("L4M Logger runs in sandbox");
			runningSandbox = true;
		}
	}
	if (!runningSandbox) {
		// do not use parent handlers but our own
		setUseParentHandlers(false);
		// and add the Lab4inf handler to our logger
		addHandler(new Lab4InfHandler());
		// register with the LogManager
	}
	LogManager manager = LogManager.getLogManager();
	Logger aLogger = manager.getLogger(loggerName);
	if (manager.getLogger(loggerName) == null) {
		if (!LogManager.getLogManager().addLogger(this)) {
			System.err.println("failed to add " + this);
			throw new RuntimeException("addding L4MLogger failed");
		}
	} else {
		String msg;
		msg = format("allready registered %s by %s", loggerName, aLogger);
		aLogger.warning(msg);
		msg = format("could not register me: %s", this);
		aLogger.warning(msg);
	}
	setLevel(Level.WARNING);
}
 
Example 8
Source File: SentryLoggerTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public static SentryHandler getSentryHandler() {
    LogManager logManager = LogManager.getLogManager();
    assertThat(logManager).isInstanceOf(org.jboss.logmanager.LogManager.class);

    DelayedHandler delayedHandler = InitialConfigurator.DELAYED_HANDLER;
    assertThat(Logger.getLogger("").getHandlers()).contains(delayedHandler);
    assertThat(delayedHandler.getLevel()).isEqualTo(Level.ALL);

    Handler handler = Arrays.stream(delayedHandler.getHandlers())
            .filter(h -> (h instanceof SentryHandler))
            .findFirst().orElse(null);
    return (SentryHandler) handler;
}
 
Example 9
Source File: PythonProject.java    From AndroidRobot with Apache License 2.0 5 votes vote down vote up
private static final void replaceAllLogFormatters(Formatter form, Level level)
/*     */   {
/* 179 */     LogManager mgr = LogManager.getLogManager();
/* 180 */     Enumeration loggerNames = mgr.getLoggerNames();
/* 181 */     while (loggerNames.hasMoreElements()) {
/* 182 */       String loggerName = (String)loggerNames.nextElement();
/* 183 */       Logger logger = mgr.getLogger(loggerName);
/* 184 */       for (Handler handler : logger.getHandlers()) {
/* 185 */         handler.setFormatter(form);
/* 186 */         handler.setLevel(level);
/*     */       }
/*     */     }
/*     */   }
 
Example 10
Source File: MemoryHandlerTest.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String... args) throws IOException {
    // load logging.propertes for the test
    String tstSrc = System.getProperty("test.src", ".");
    File fname = new File(tstSrc, LM_PROP_FNAME);
    String prop = fname.getCanonicalPath();
    System.setProperty(CFG_FILE_PROP, prop);
    LogManager.getLogManager();
    // create a logger
    logger = Logger.getLogger(MemoryHandlerTest.class.getName());
    // don't have parent handlers get log messages
    logger.setUseParentHandlers(false);
    //
    // Test 1,2: create a CustomMemoryHandler which in the config has
    // specified a target of CustomTargetHandler.  (1) Make sure that it
    // is created and (2) that the target handler is loaded.
    //
    CustomMemoryHandler cmh = new CustomMemoryHandler();
    try {
        logger.addHandler(cmh);
    } catch (RuntimeException rte) {
        throw new RuntimeException(
            "Test Failed: did not load java.util.logging.ConsoleHandler as expected",
            rte);
    }
    // if we get here and our config has been processed properly, then we
    // should have loaded our target handler
    if (CustomTargetHandler.numLoaded !=1) {
        throw new RuntimeException(
            "Test failed: did not load CustomTargetHandler as expected");
    }
    //
    // Test 3: try to add a handler with no target.  This should fail with
    // an exception
    CustomMemoryHandlerNoTarget cmhnt = null;
    try {
        cmhnt = new CustomMemoryHandlerNoTarget();
    } catch (RuntimeException re) {
        // expected -- no target specified
        System.out.println("Info: " + re.getMessage() + " as expected.");
    }
    if (cmhnt != null) {
        throw new RuntimeException(
            "Test Failed: erroneously loaded CustomMemoryHandlerNoTarget");
    }

    // Test 4: log a message and check that the target handler is actually used
    logger.log(Level.WARNING, "Unused");
    if (CustomTargetHandler.numPublished != 1) {
        throw new RuntimeException("Test failed: CustomTargetHandler was not used");
    }

    // Test 5: make sure that SimpleTargetHandler hasn't been erroneously called
    if (SimpleTargetHandler.numPublished != 0) {
        throw new RuntimeException("Test failed: SimpleTargetHandler has been used");
    }

    // Test 6: try using SimpleTargetHanlder via standard MemoryHandler
    // (which has target set to SimpleTargetHandler)
    MemoryHandler mh = new MemoryHandler();
    mh.publish(new LogRecord(Level.INFO, "Unused msg to MemoryHandler"));
    // see if it made it to the SimpleTargetHandler
    if (SimpleTargetHandler.numPublished != 1) {
        throw new RuntimeException("Test failed: SimpleTargetHandler was not used");
    }
}
 
Example 11
Source File: Main.java    From lancoder with GNU General Public License v3.0 4 votes vote down vote up
private static void buildLoggers(int verbosity) {
	Level loggingLevel = Level.SEVERE;

	if (verbosity > 6) {
		verbosity = 6;
	}

	switch (verbosity) {
	case 1:
		loggingLevel = Level.SEVERE;
		break;
	case 2:
		loggingLevel = Level.WARNING;
		break;
	case 3:
		loggingLevel = Level.INFO;
		break;
	case 4:
		loggingLevel = Level.FINE;
		break;
	case 5:
		loggingLevel = Level.FINER;
		break;
	case 6:
		loggingLevel = Level.FINEST;
		break;
	default:
		loggingLevel = Level.INFO;
	}

	LogManager manager = LogManager.getLogManager();
	manager.reset();

	logger.setLevel(loggingLevel);

	ConsoleHandler handler = new ConsoleHandler();
	handler.setLevel(loggingLevel);
	handler.setFormatter(new LogFormatter());
	logger.addHandler(handler);

	manager.addLogger(logger);
}
 
Example 12
Source File: LoggingDeadlock2.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) throws Throwable {
    final CyclicBarrier startingGate = new CyclicBarrier(2);
    final Throwable[] thrown = new Throwable[1];

    // Some random variation, to help tickle races.
    final Random rnd = new Random();
    final boolean dojoin = rnd.nextBoolean();
    final int JITTER = 1024;
    final int iters1 = rnd.nextInt(JITTER);
    final int iters2 = JITTER - iters1;
    final AtomicInteger counter = new AtomicInteger(0);

    Thread exiter = new Thread() {
        public void run() {
            try {
                startingGate.await();
                for (int i = 0; i < iters1; i++)
                    counter.getAndIncrement();
                System.exit(99);
            } catch (Throwable t) {
                t.printStackTrace();
                System.exit(86);
            }
        }};
    exiter.start();

    startingGate.await();
    for (int i = 0; i < iters2; i++)
        counter.getAndIncrement();
    // This may or may not result in a first call to
    // Runtime.addShutdownHook after shutdown has already
    // commenced.
    LogManager.getLogManager();

    if (dojoin) {
        exiter.join();
        if (thrown[0] != null)
            throw new Error(thrown[0]);
        check(counter.get() == JITTER);
    }
}
 
Example 13
Source File: Listeners.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
    LogManager logman = LogManager.getLogManager();

    Listener[] listeners = new Listener[2];
    Listener listener1 = listeners[0] = new Listener(LogManager.class);
    Listener listener2 = listeners[1] = new Listener(LogManager.class);

    // add listeners
    logman.addPropertyChangeListener(listener1);
    test(listeners, 1, 0);

    logman.addPropertyChangeListener(listener1);
    test(listeners, 2, 0);

    logman.addPropertyChangeListener(listener2);
    test(listeners, 2, 1);

    // null handling to check for impact on the existing registrations
    try {
        logman.addPropertyChangeListener(null);
        assertTrue(false, "NullPointerException expected");
    } catch (NullPointerException expected) { }
    test(listeners, 2, 1);

    logman.removePropertyChangeListener(null);  // no-op
    test(listeners, 2, 1);

    // remove listeners
    logman.removePropertyChangeListener(listener1);
    test(listeners, 1, 1);

    logman.removePropertyChangeListener(listener1);
    test(listeners, 0, 1);

    logman.removePropertyChangeListener(listener1);  // no-op
    test(listeners, 0, 1);

    logman.removePropertyChangeListener(listener2);
    test(listeners, 0, 0);

    logman.removePropertyChangeListener(listener2);  // no-op
    test(listeners, 0, 0);
}
 
Example 14
Source File: MemoryHandlerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String... args) throws IOException {
    // load logging.propertes for the test
    String tstSrc = System.getProperty("test.src", ".");
    File fname = new File(tstSrc, LM_PROP_FNAME);
    String prop = fname.getCanonicalPath();
    System.setProperty(CFG_FILE_PROP, prop);
    LogManager.getLogManager();
    // create a logger
    logger = Logger.getLogger(MemoryHandlerTest.class.getName());
    // don't have parent handlers get log messages
    logger.setUseParentHandlers(false);
    //
    // Test 1,2: create a CustomMemoryHandler which in the config has
    // specified a target of CustomTargetHandler.  (1) Make sure that it
    // is created and (2) that the target handler is loaded.
    //
    CustomMemoryHandler cmh = new CustomMemoryHandler();
    try {
        logger.addHandler(cmh);
    } catch (RuntimeException rte) {
        throw new RuntimeException(
            "Test Failed: did not load java.util.logging.ConsoleHandler as expected",
            rte);
    }
    // if we get here and our config has been processed properly, then we
    // should have loaded our target handler
    if (CustomTargetHandler.numLoaded !=1) {
        throw new RuntimeException(
            "Test failed: did not load CustomTargetHandler as expected");
    }
    //
    // Test 3: try to add a handler with no target.  This should fail with
    // an exception
    CustomMemoryHandlerNoTarget cmhnt = null;
    try {
        cmhnt = new CustomMemoryHandlerNoTarget();
    } catch (RuntimeException re) {
        // expected -- no target specified
        System.out.println("Info: " + re.getMessage() + " as expected.");
    }
    if (cmhnt != null) {
        throw new RuntimeException(
            "Test Failed: erroneously loaded CustomMemoryHandlerNoTarget");
    }

    // Test 4: log a message and check that the target handler is actually used
    logger.log(Level.WARNING, "Unused");
    if (CustomTargetHandler.numPublished != 1) {
        throw new RuntimeException("Test failed: CustomTargetHandler was not used");
    }

    // Test 5: make sure that SimpleTargetHandler hasn't been erroneously called
    if (SimpleTargetHandler.numPublished != 0) {
        throw new RuntimeException("Test failed: SimpleTargetHandler has been used");
    }

    // Test 6: try using SimpleTargetHanlder via standard MemoryHandler
    // (which has target set to SimpleTargetHandler)
    MemoryHandler mh = new MemoryHandler();
    mh.publish(new LogRecord(Level.INFO, "Unused msg to MemoryHandler"));
    // see if it made it to the SimpleTargetHandler
    if (SimpleTargetHandler.numPublished != 1) {
        throw new RuntimeException("Test failed: SimpleTargetHandler was not used");
    }
}
 
Example 15
Source File: TestGetLoggerNPE.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    final String testCase = args.length == 0 ? "getLogger" : args[0];
    final JavaAWTAccessStub access = new JavaAWTAccessStub();
    SharedSecrets.setJavaAWTAccess(access);
    final ThreadGroup tg = new ThreadGroup("TestGroup");
    Thread t = new Thread(tg, "test") {
        public void run() {
            try {
                access.setContext(Context.ONE);
                final PrintStream out = System.out;
                System.setOut(null);
                try {
                    if ("getLogger".equals(testCase)) {
                       Logger.getLogger("sun.plugin");
                    } else {
                       LogManager.getLogManager();
                    }
                } finally {
                    System.setOut(out);
                }

                System.out.println(Logger.global);
            } catch (Throwable x) {
                x.printStackTrace();
                thrown = x;
            }
        }
    };
    Policy.setPolicy(new Policy() {
         public boolean implies(ProtectionDomain domain,
                                Permission permission) {
             return true; // all permissions
         }
    });
    System.setSecurityManager(new SecurityManager());
    t.start();
    t.join();
    if (thrown == null) {
        System.out.println("PASSED: " + testCase);
    } else {
        System.err.println("FAILED: " + testCase);
        throw new Error("Test failed: " + testCase + " - " + thrown, thrown);
    }

}
 
Example 16
Source File: LoggerUnitTest.java    From candybean with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * A system test for a logger configured using the candybean logger
 * configuration.
 * 
 * @throws Exception
 */
@Test
public void cbConfiguredLogger() throws Exception {
	String name1 = this.getClass().getSimpleName() + "1";
	String name2 = this.getClass().getSimpleName() + "2";
	String config1Path = Candybean.ROOT_DIR + File.separator + name1 + ".config";
	String config2Path = Candybean.ROOT_DIR + File.separator + name2 + ".config";
	String log1Path = Candybean.ROOT_DIR + File.separator + "log" + File.separator + name1 + ".log";
	String log2Path = Candybean.ROOT_DIR + File.separator + "log" + File.separator + name2 + ".log";
	
	// Load the initial properties from the candybean config file
       Properties initialProperties = candybean.config.getPropertiesCopy();
	
	// Change the FileHandler Formatter to XMLFormatter
	initialProperties.setProperty("java.util.logging.FileHandler.formatter", "java.util.logging.XMLFormatter");
	initialProperties.setProperty("java.util.logging.ConsoleHandler.formatter", "java.util.logging.XMLFormatter");
	
	// Create a new config file and write props to that file
	File config1File = new File(config1Path);
	config1File.createNewFile();
	initialProperties.store(new FileOutputStream(config1File), null);

	// Update the system property that specifies where to load the logging configuration from.
	System.setProperty("java.util.logging.config.file", config1Path);
	LogManager.getLogManager().readConfiguration();
	logger = Logger.getLogger(this.getClass().getSimpleName());
	
	// Log to file and verify text
	File log1File = new File(log1Path);
	FileHandler firstFileHandler = new FileHandler(log1Path);
	logger.addHandler(firstFileHandler);
	logger.info("First logged message configured using candybean configuration file");
	assertTrue(log1File.exists());
	assertEquals(getLinesInLogFile(log1File), 14);
	
	// Change the FileHandler Formatter to SimpleFormatter
	initialProperties.setProperty("java.util.logging.FileHandler.formatter", "java.util.logging.SimpleFormatter");
	initialProperties.setProperty("java.util.logging.ConsoleHandler.formatter", "java.util.logging.SimpleFormatter");
	
	// Create a second config file and write props to that file
	File config2File = new File(config2Path);
	config2File.createNewFile();
	initialProperties.store(new FileOutputStream(config2File), null);

	// Update the system property that specifies where to load the logging configuration from.
	System.setProperty("java.util.logging.config.file", config2Path);
	LogManager.getLogManager().readConfiguration();
	logger = Logger.getLogger(this.getClass().getSimpleName());
	
	// Log to file and verify text
	File log2File = new File(log2Path);
	FileHandler secondFileHandler = new FileHandler(log2Path);
	logger.addHandler(secondFileHandler);
	logger.info("Second logged message configured using different candybean configuration file");
	assertTrue(log2File.exists());
	assertTrue(getLinesInLogFile(log2File) < 13);
	
	// Reset the logging config file path to the default and re-read the configuration
	System.setProperty("java.util.logging.config.file", candybean.config.configFile.getCanonicalPath());
	LogManager logManager = LogManager.getLogManager();
	logManager.readConfiguration();
	
	// Delete all created configuration and log files
	config1File.delete();
	log1File.delete();
	config2File.delete();
	log2File.delete();
}
 
Example 17
Source File: Listeners.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
    LogManager logman = LogManager.getLogManager();

    Listener[] listeners = new Listener[2];
    Listener listener1 = listeners[0] = new Listener(LogManager.class);
    Listener listener2 = listeners[1] = new Listener(LogManager.class);

    // add listeners
    logman.addPropertyChangeListener(listener1);
    test(listeners, 1, 0);

    logman.addPropertyChangeListener(listener1);
    test(listeners, 2, 0);

    logman.addPropertyChangeListener(listener2);
    test(listeners, 2, 1);

    // null handling to check for impact on the existing registrations
    try {
        logman.addPropertyChangeListener(null);
        assertTrue(false, "NullPointerException expected");
    } catch (NullPointerException expected) { }
    test(listeners, 2, 1);

    logman.removePropertyChangeListener(null);  // no-op
    test(listeners, 2, 1);

    // remove listeners
    logman.removePropertyChangeListener(listener1);
    test(listeners, 1, 1);

    logman.removePropertyChangeListener(listener1);
    test(listeners, 0, 1);

    logman.removePropertyChangeListener(listener1);  // no-op
    test(listeners, 0, 1);

    logman.removePropertyChangeListener(listener2);
    test(listeners, 0, 0);

    logman.removePropertyChangeListener(listener2);  // no-op
    test(listeners, 0, 0);
}
 
Example 18
Source File: MemoryHandlerTest.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String... args) throws IOException {
    // load logging.propertes for the test
    String tstSrc = System.getProperty("test.src", ".");
    File fname = new File(tstSrc, LM_PROP_FNAME);
    String prop = fname.getCanonicalPath();
    System.setProperty(CFG_FILE_PROP, prop);
    LogManager.getLogManager();
    // create a logger
    logger = Logger.getLogger(MemoryHandlerTest.class.getName());
    // don't have parent handlers get log messages
    logger.setUseParentHandlers(false);
    //
    // Test 1,2: create a CustomMemoryHandler which in the config has
    // specified a target of CustomTargetHandler.  (1) Make sure that it
    // is created and (2) that the target handler is loaded.
    //
    CustomMemoryHandler cmh = new CustomMemoryHandler();
    try {
        logger.addHandler(cmh);
    } catch (RuntimeException rte) {
        throw new RuntimeException(
            "Test Failed: did not load java.util.logging.ConsoleHandler as expected",
            rte);
    }
    // if we get here and our config has been processed properly, then we
    // should have loaded our target handler
    if (CustomTargetHandler.numLoaded !=1) {
        throw new RuntimeException(
            "Test failed: did not load CustomTargetHandler as expected");
    }
    //
    // Test 3: try to add a handler with no target.  This should fail with
    // an exception
    CustomMemoryHandlerNoTarget cmhnt = null;
    try {
        cmhnt = new CustomMemoryHandlerNoTarget();
    } catch (RuntimeException re) {
        // expected -- no target specified
        System.out.println("Info: " + re.getMessage() + " as expected.");
    }
    if (cmhnt != null) {
        throw new RuntimeException(
            "Test Failed: erroneously loaded CustomMemoryHandlerNoTarget");
    }

    // Test 4: log a message and check that the target handler is actually used
    logger.log(Level.WARNING, "Unused");
    if (CustomTargetHandler.numPublished != 1) {
        throw new RuntimeException("Test failed: CustomTargetHandler was not used");
    }

    // Test 5: make sure that SimpleTargetHandler hasn't been erroneously called
    if (SimpleTargetHandler.numPublished != 0) {
        throw new RuntimeException("Test failed: SimpleTargetHandler has been used");
    }

    // Test 6: try using SimpleTargetHanlder via standard MemoryHandler
    // (which has target set to SimpleTargetHandler)
    MemoryHandler mh = new MemoryHandler();
    mh.publish(new LogRecord(Level.INFO, "Unused msg to MemoryHandler"));
    // see if it made it to the SimpleTargetHandler
    if (SimpleTargetHandler.numPublished != 1) {
        throw new RuntimeException("Test failed: SimpleTargetHandler was not used");
    }
}
 
Example 19
Source File: MemoryHandlerTest.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String... args) throws IOException {
    // load logging.propertes for the test
    String tstSrc = System.getProperty("test.src", ".");
    File fname = new File(tstSrc, LM_PROP_FNAME);
    String prop = fname.getCanonicalPath();
    System.setProperty(CFG_FILE_PROP, prop);
    LogManager.getLogManager();
    // create a logger
    logger = Logger.getLogger(MemoryHandlerTest.class.getName());
    // don't have parent handlers get log messages
    logger.setUseParentHandlers(false);
    //
    // Test 1,2: create a CustomMemoryHandler which in the config has
    // specified a target of CustomTargetHandler.  (1) Make sure that it
    // is created and (2) that the target handler is loaded.
    //
    CustomMemoryHandler cmh = new CustomMemoryHandler();
    try {
        logger.addHandler(cmh);
    } catch (RuntimeException rte) {
        throw new RuntimeException(
            "Test Failed: did not load java.util.logging.ConsoleHandler as expected",
            rte);
    }
    // if we get here and our config has been processed properly, then we
    // should have loaded our target handler
    if (CustomTargetHandler.numLoaded !=1) {
        throw new RuntimeException(
            "Test failed: did not load CustomTargetHandler as expected");
    }
    //
    // Test 3: try to add a handler with no target.  This should fail with
    // an exception
    CustomMemoryHandlerNoTarget cmhnt = null;
    try {
        cmhnt = new CustomMemoryHandlerNoTarget();
    } catch (RuntimeException re) {
        // expected -- no target specified
        System.out.println("Info: " + re.getMessage() + " as expected.");
    }
    if (cmhnt != null) {
        throw new RuntimeException(
            "Test Failed: erroneously loaded CustomMemoryHandlerNoTarget");
    }

    // Test 4: log a message and check that the target handler is actually used
    logger.log(Level.WARNING, "Unused");
    if (CustomTargetHandler.numPublished != 1) {
        throw new RuntimeException("Test failed: CustomTargetHandler was not used");
    }

    // Test 5: make sure that SimpleTargetHandler hasn't been erroneously called
    if (SimpleTargetHandler.numPublished != 0) {
        throw new RuntimeException("Test failed: SimpleTargetHandler has been used");
    }

    // Test 6: try using SimpleTargetHanlder via standard MemoryHandler
    // (which has target set to SimpleTargetHandler)
    MemoryHandler mh = new MemoryHandler();
    mh.publish(new LogRecord(Level.INFO, "Unused msg to MemoryHandler"));
    // see if it made it to the SimpleTargetHandler
    if (SimpleTargetHandler.numPublished != 1) {
        throw new RuntimeException("Test failed: SimpleTargetHandler was not used");
    }
}
 
Example 20
Source File: TestGetLoggerNPE.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    final String testCase = args.length == 0 ? "getLogger" : args[0];
    final JavaAWTAccessStub access = new JavaAWTAccessStub();
    SharedSecrets.setJavaAWTAccess(access);
    final ThreadGroup tg = new ThreadGroup("TestGroup");
    Thread t = new Thread(tg, "test") {
        public void run() {
            try {
                access.setContext(Context.ONE);
                final PrintStream out = System.out;
                System.setOut(null);
                try {
                    if ("getLogger".equals(testCase)) {
                       Logger.getLogger("sun.plugin");
                    } else {
                       LogManager.getLogManager();
                    }
                } finally {
                    System.setOut(out);
                }

                System.out.println(Logger.global);
            } catch (Throwable x) {
                x.printStackTrace();
                thrown = x;
            }
        }
    };
    Policy.setPolicy(new Policy() {
         public boolean implies(ProtectionDomain domain,
                                Permission permission) {
             return true; // all permissions
         }
    });
    System.setSecurityManager(new SecurityManager());
    t.start();
    t.join();
    if (thrown == null) {
        System.out.println("PASSED: " + testCase);
    } else {
        System.err.println("FAILED: " + testCase);
        throw new Error("Test failed: " + testCase + " - " + thrown, thrown);
    }

}