java.util.logging.LogManager Java Examples

The following examples show how to use java.util.logging.LogManager. 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: TestAppletLoggerContext.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void testLoadingMain() {
    Bridge.desactivate();

    Logger bar = new Bridge.CustomLogger("com.foo.Bar");
    LogManager.getLogManager().addLogger(bar);
    assertNotNull(bar.getParent());
    testParent(bar);
    testParent(LogManager.getLogManager().getLogger("global"));
    testParent(LogManager.getLogManager().getLogger(bar.getName()));

    Bridge.changeContext();

    Logger foo = new Bridge.CustomLogger("com.foo.Foo");
    boolean b = LogManager.getLogManager().addLogger(foo);
    assertEquals(Boolean.TRUE, Boolean.valueOf(b));
    assertNotNull(foo.getParent());
    testParent(foo);
    testParent(LogManager.getLogManager().getLogger("global"));
    testParent(LogManager.getLogManager().getLogger(foo.getName()));

}
 
Example #2
Source File: Catalina.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void run() {
    try {
        if (getServer() != null) {
            Catalina.this.stop();
        }
    } catch (Throwable ex) {
        ExceptionUtils.handleThrowable(ex);
        log.error(sm.getString("catalina.shutdownHookFail"), ex);
    } finally {
        // If JULI is used, shut JULI down *after* the server shuts down
        // so log messages aren't lost
        LogManager logManager = LogManager.getLogManager();
        if (logManager instanceof ClassLoaderLogManager) {
            ((ClassLoaderLogManager) logManager).shutdown();
        }
    }
}
 
Example #3
Source File: Main.java    From copybara with Apache License 2.0 6 votes vote down vote up
protected void configureLog(FileSystem fs, String[] args) throws IOException {
  String baseDir = getBaseExecDir();
  Files.createDirectories(fs.getPath(baseDir));
  if (System.getProperty("java.util.logging.config.file") == null) {
    logger.atInfo().log("Setting up LogManager");
    String level = isEnableLogging(args) ? "INFO" : "OFF";
    LogManager.getLogManager().readConfiguration(new ByteArrayInputStream((
        "handlers=java.util.logging.FileHandler\n"
            + ".level=INFO\n"
            + "java.util.logging.FileHandler.level=" + level +"\n"
            + "java.util.logging.FileHandler.pattern="
            + baseDir + "/copybara-%g.log\n"
            + "java.util.logging.FileHandler.count=10\n"
            + "java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter\n"
            + "java.util.logging.SimpleFormatter.format="
            + "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$-6s %2$s %5$s%6$s%n")
        .getBytes(StandardCharsets.UTF_8)
    ));
  }
}
 
Example #4
Source File: LoggingDeadlock.java    From openjdk-jdk8u-backup 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: NbErrorManagerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testLog() throws Exception {
    assertFalse(err.isLoggable(ErrorManager.INFORMATIONAL));
    err.log("some msg");
    String s = readLog();
    assertTrue(s.indexOf("some msg") == -1);
    assertTrue(err.isLoggable(ErrorManager.WARNING));
    err.log(ErrorManager.WARNING, "another msg");
    s = readLog();
    assertTrue(s.indexOf("another msg") != -1);
    ErrorManager err2 = err.getInstance("foo.bar.baz");
    assertFalse(err2.isLoggable(ErrorManager.INFORMATIONAL));
    err2.log("sub msg #1");
    s = readLog();
    assertTrue(s.indexOf("sub msg #1") == -1);
    System.setProperty("quux.hoho.level", "0");

    LogManager.getLogManager().readConfiguration();

    err2 = err.getInstance("quux.hoho.yaya");
    assertTrue(err2.isLoggable(ErrorManager.INFORMATIONAL));
    err2.log("sub msg #2");
    s = readLog();
    assertTrue(s, s.indexOf("sub msg #2") != -1);
    assertTrue(s, s.indexOf("quux.hoho.yaya") != -1);
}
 
Example #6
Source File: ClassLoaders.java    From brave with Apache License 2.0 6 votes vote down vote up
/** Runs the type in a new classloader that recreates brave classes */
public static void assertRunIsUnloadable(Class<? extends Runnable> runnable, ClassLoader parent) {
  // We can't use log4j2's log manager. More importantly, we want to make sure loggers don't hold
  // our test classloader from being collected.
  System.setProperty("java.util.logging.manager", LogManager.class.getName());
  assertThat(LogManager.getLogManager().getClass()).isSameAs(LogManager.class);

  WeakReference<ClassLoader> loader;
  try {
    loader = invokeRunFromNewClassLoader(runnable, parent);
  } catch (Exception e) {
    throw new AssertionError(e);
  }

  GarbageCollectors.blockOnGC();

  assertThat(loader.get())
    .withFailMessage(runnable + " includes state that couldn't be garbage collected")
    .isNull();
}
 
Example #7
Source File: LogUtil.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public static void readJavaUtilLoggingConfigFromClasspath() {
  InputStream inputStream = ReflectUtil.getResourceAsStream("logging.properties");
  try {
    if (inputStream != null) {
      LogManager.getLogManager().readConfiguration(inputStream);

      String redirectCommons = LogManager.getLogManager().getProperty("redirect.commons.logging");
      if ((redirectCommons != null) && (!redirectCommons.equalsIgnoreCase("false"))) {
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
      }
    }
  } catch (Exception e) {
    throw new PvmException("couldn't initialize logging properly", e);
  } finally {
    IoUtil.closeSilently(inputStream);
  }
}
 
Example #8
Source File: LogManagerHelper.java    From syslog-java-client with MIT License 6 votes vote down vote up
/**
 * Visible version of {@link java.util.logging.LogManager#getFilterProperty(String, java.util.logging.Filter)}.
 *
 * We return an instance of the class named by the "name" property.
 *
 * If the property is not defined or has problems we return the defaultValue.
 */
@Nullable
public static Filter getFilterProperty(@Nonnull LogManager manager, @Nullable String name, @Nullable Filter defaultValue) {
    if (name == null) {
        return defaultValue;
    }
    String val = manager.getProperty(name);
    try {
        if (val != null) {
            Class clz = ClassLoader.getSystemClassLoader().loadClass(val);
            return (Filter) clz.newInstance();
        }
    } catch (Exception ex) {
        // We got one of a variety of exceptions in creating the
        // class or creating an instance.
        // Drop through.
    }
    // We got an exception.  Return the defaultValue.
    return defaultValue;
}
 
Example #9
Source File: ThreadedFileHandler.java    From xframium-java with GNU General Public License v3.0 6 votes vote down vote up
public void configureHandler( Level baseLevel )
{
    
    
    Handler[] hList = LogManager.getLogManager().getLogger( "" ).getHandlers();
    for ( Handler h : hList )
    {
        if ( h instanceof ThreadedFileHandler )
            return;
    }
    
    setLevel( baseLevel );
    setFormatter( new SimpleFormatter() );
    
    LogManager.getLogManager().getLogger( "" ).addHandler( this );
}
 
Example #10
Source File: Listeners.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Tests that the given listeners are invoked the expected number of
 * times.
 */
static void test(Listener[] listeners, int... expected) throws Exception {
    // reset counts
    for (Listener listener : listeners) {
        listener.reset();
    }

    // re-reading configuration causes events to be fired
    LogManager.getLogManager().readConfiguration();

    // check event listeners invoked as expected
    for (int i = 0; i < expected.length; i++) {
        assertTrue(listeners[i].fireCount() == expected[i],
            "Unexpected event count");
    }
}
 
Example #11
Source File: TestAppletLoggerContext.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void testLoadingMain() {
    Bridge.desactivate();

    Logger bar = new Bridge.CustomLogger("com.foo.Bar");
    LogManager.getLogManager().addLogger(bar);
    assertNotNull(bar.getParent());
    testParent(bar);
    testParent(LogManager.getLogManager().getLogger("global"));
    testParent(LogManager.getLogManager().getLogger(bar.getName()));

    Bridge.changeContext();

    Logger foo = new Bridge.CustomLogger("com.foo.Foo");
    boolean b = LogManager.getLogManager().addLogger(foo);
    assertEquals(Boolean.TRUE, Boolean.valueOf(b));
    assertNotNull(foo.getParent());
    testParent(foo);
    testParent(LogManager.getLogManager().getLogger("global"));
    testParent(LogManager.getLogManager().getLogger(foo.getName()));

}
 
Example #12
Source File: LoggingDeadlock.java    From openjdk-8-source 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 #13
Source File: TopLoggingTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testCanInfluenceBehaviourBySettingALevelPropertyOnExistingParent() throws Exception {
    System.setProperty("ha.nu.level", "100");

    Logger l = Logger.getLogger("ha.nu.wirta");

    LogManager.getLogManager().readConfiguration();

    l.log(Level.FINER, "Finer level msg");

    Pattern p = Pattern.compile("FINER.*Finer level msg");
    String disk = readLog(true);
    Matcher d = p.matcher(disk);

    if (!d.find()) {
        fail("msg shall be logged to file: " + disk);
    }
}
 
Example #14
Source File: Logging.java    From org.openntf.domino with Apache License 2.0 6 votes vote down vote up
/**
 * Activates default configuration when a configuration file is missing.
 *
 * @throws IOException
 */
private void startUpFallback() throws IOException {
	String pattern = Factory.getDataPath() + "/IBM_TECHNICAL_SUPPORT/org.openntf.%u.%g.log";
	Logger oodLogger = Logger.getLogger("org.openntf.domino");
	oodLogger.setLevel(Level.WARNING);

	DefaultFileHandler dfh = new DefaultFileHandler(pattern, 50000, 100, true);
	dfh.setFormatter(new FileFormatter());
	dfh.setLevel(Level.WARNING);
	oodLogger.addHandler(dfh);

	DefaultConsoleHandler dch = new DefaultConsoleHandler();
	dch.setFormatter(new ConsoleFormatter());
	dch.setLevel(Level.WARNING);
	oodLogger.addHandler(dch);

	OpenLogHandler olh = new OpenLogHandler();
	olh.setLogDbPath("OpenLog.nsf");
	olh.setLevel(Level.WARNING);
	oodLogger.addHandler(olh);

	LogManager.getLogManager().addLogger(oodLogger);
}
 
Example #15
Source File: TestAppletLoggerContext.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void testThree() {
    for (int i=0; i<3 ; i++) {
        Logger logger1 = LogManager.getLogManager().getLogger("");
        Logger logger1b = LogManager.getLogManager().getLogger("");
        assertNotNull(logger1);
        assertNotNull(logger1b);
        assertEquals(logger1, logger1b);
        Bridge.changeContext();
        Logger logger2 = LogManager.getLogManager().getLogger("");
        Logger logger2b = LogManager.getLogManager().getLogger("");
        assertNotNull(logger2);
        assertNotNull(logger2b);
        assertEquals(logger2, logger2b);
        assertEquals(logger1, logger2);
    }
}
 
Example #16
Source File: TestAppletLoggerContext.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void testFive() {
    for (int i=0; i<3 ; i++) {
        Logger logger1 = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME);
        Logger logger1b = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME);
        assertNotNull(logger1);
        assertNotNull(logger1b);
        assertEquals(logger1, logger1b);

        Bridge.changeContext();

        Logger logger2 = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME);
        Logger logger2b = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME);
        assertNotNull(logger2);
        assertNotNull(logger2b);
        assertEquals(logger2, logger2b);

        assertEquals(logger1, logger2);
    }
}
 
Example #17
Source File: TestConfigurationLock.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run() {
    while (goOn) {
        try {
            if (Math.random() > CONFSYNCTHRESHOLD) {
                // calling readConfiguration while holding a lock can
                // increase deadlock probability...
                synchronized(fakeConfExternalLock()) {
                    LogManager.getLogManager().readConfiguration();
                }
            } else {
                LogManager.getLogManager().readConfiguration();
            }
            Logger blah = Logger.getLogger(BLAH);
            blah.setLevel(Level.FINEST);
            blah.fine(BLAH);
            readCount.incrementAndGet();
            pause(1);
        } catch (Exception x) {
            fail(x);
        }
    }
}
 
Example #18
Source File: ClassLogger.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
public static @Nullable ClassLogger find(@Nullable Logger parent, Class<?> klass, @Nullable String instanceKey) {
    if(parent == null) {
        parent = Logger.getLogger("");
    }

    String name = getName(klass, instanceKey);
    if(parent instanceof ClassLogger && Objects.equals(parent.getName(), name)) {
        // If the given parent logger looks exactly like the logger
        // we are supposed to return, just use it. This makes it easy
        // to replace a parent logger with a child once only e.g.
        //
        //     logger = ClassLogger.get(logger, getClass(), "myInstance")
        return (ClassLogger) parent;
    }

    LogManager lm = LogManager.getLogManager();
    Logger logger = lm.getLogger(name);
    if(logger instanceof ClassLogger) {
        if(parent != logger.getParent()) {
            throw new IllegalStateException("Already registred logger " + name + " has a different parent than the one requested:\n  old = " + logger.getParent() + "\n  new = " + parent);
        }
        return (ClassLogger) logger;
    } else {
        return null;
    }
}
 
Example #19
Source File: Listeners.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Tests that the given listeners are invoked the expected number of
 * times.
 */
static void test(Listener[] listeners, int... expected) throws Exception {
    // reset counts
    for (Listener listener : listeners) {
        listener.reset();
    }

    // re-reading configuration causes events to be fired
    LogManager.getLogManager().readConfiguration();

    // check event listeners invoked as expected
    for (int i = 0; i < expected.length; i++) {
        assertTrue(listeners[i].fireCount() == expected[i],
            "Unexpected event count");
    }
}
 
Example #20
Source File: TestLogConfigurationDeadLock.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    while (goOn) {
        try {
            LogManager.getLogManager().readConfiguration();
            readCount.incrementAndGet();
            Thread.sleep(1);
        } catch (Exception x) {
            fail(x);
        }
    }
}
 
Example #21
Source File: TestLogConfigurationDeadLock.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
    while (goOn) {
        try {
            LogManager.getLogManager().readConfiguration();
            readCount.incrementAndGet();
            Thread.sleep(1);
        } catch (Exception x) {
            fail(x);
        }
    }
}
 
Example #22
Source File: SimpleUpdateConfigWithInputStreamTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void updateConfigurationWith(Properties propertyFile,
        Function<String,BiFunction<String,String,String>> remapper) {
    try {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        propertyFile.store(bytes, propertyFile.getProperty("test.name"));
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes.toByteArray());
        LogManager.getLogManager().updateConfiguration(bais, remapper);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #23
Source File: FileHandler.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private String getProperty(String name, String defaultValue) {
    String value = LogManager.getLogManager().getProperty(name);
    if (value == null) {
        value = defaultValue;
    } else {
        value = value.trim();
    }
    return value;
}
 
Example #24
Source File: FileHandlerQuerierTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void getLoggerFilePath_onVariablesInPath_fails() throws Exception {
  LogManager mockLogManager = Mockito.mock(LogManager.class);
  when(mockLogManager.getProperty("java.util.logging.FileHandler.pattern"))
      .thenReturn(tmp.getRoot() + File.separator + "hello_%u.log");
  Logger logger =
      getLoggerWithFileHandler(Paths.get(tmp.getRoot().toString(), "hello_0.log"));
  FileHandlerQuerier handlerQuerier = new FileHandlerQuerier();

  assertThrows(IllegalStateException.class, () -> handlerQuerier.getLoggerFilePath(logger));
}
 
Example #25
Source File: LocalFileHandler.java    From tomee with Apache License 2.0 5 votes vote down vote up
protected String getProperty(final String name, final String defaultValue) {
    String value = LogManager.getLogManager().getProperty(name);
    if (value == null) {
        value = defaultValue;
    } else {
        value = value.trim();
    }
    return value;
}
 
Example #26
Source File: LoggerFinderBackendTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
Logger getBackendLogger(String name) {
    if (isSystem) {
        return LoggingProviderImpl.getLogManagerAccess().demandLoggerFor(
                LogManager.getLogManager(), name, Thread.class.getModule());
    } else {
        return Logger.getLogger(name);
    }
}
 
Example #27
Source File: MonitorDemo.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
public static void main(String[] args) throws Exception
{
    // Configure logging
    LogManager.getLogManager().readConfiguration(PVASettings.class.getResourceAsStream("/pva_logging.properties"));
    final Logger root = Logger.getLogger("");
    // Profiler shows blocking in ConsoleHandler,
    // so reduce log messages to only warnings for performance tests
    root.setLevel(Level.WARNING);
    for (Handler handler : root.getHandlers())
        handler.setLevel(root.getLevel());

    // Start PVA servers
    ForkJoinPool.commonPool().submit(() -> ConnectDemo.serve("demo1", TimeUnit.MILLISECONDS, 10));
    ForkJoinPool.commonPool().submit(() -> ConnectDemo.serve("demo2", TimeUnit.MILLISECONDS, 10));
    ForkJoinPool.commonPool().submit(() -> ConnectDemo.serve("demo3", TimeUnit.MILLISECONDS, 10));

    // PVA Client
    final PVAClient pva = new PVAClient();
    final PVAChannel ch1 = pva.getChannel("demo1");
    final PVAChannel ch2 = pva.getChannel("demo2");
    final PVAChannel ch3 = pva.getChannel("demo3");
    CompletableFuture.allOf(ch1.connect(), ch2.connect(), ch3.connect()).get();

    final MonitorListener listener = (ch, changes, overruns, data) ->
    {
        System.out.println(ch.getName() + " = " + data.get("value") + " " + overruns);
    };
    ch1.subscribe("", listener );
    ch2.subscribe("", listener);
    ch3.subscribe("", listener);

    synchronized (MonitorDemo.class)
    {
        MonitorDemo.class.wait();
    }
}
 
Example #28
Source File: RootLevelInConfigFile.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    System.setProperty(CONFIG_FILE_KEY,
            new File(System.getProperty("test.src", "."),
                    "rootlogger.properties").getAbsolutePath());
    System.out.println(CONFIG_FILE_KEY + "="
            + System.getProperty(CONFIG_FILE_KEY));
    if (! new File(System.getProperty(CONFIG_FILE_KEY)).canRead()) {
        throw new RuntimeException("can't read config file: "
                + System.getProperty(CONFIG_FILE_KEY));
    }

    final String configFile = System.getProperty(CONFIG_FILE_KEY);

    test("no security");

    LogManager.getLogManager().readConfiguration();

    Policy.setPolicy(new SimplePolicy(configFile));
    System.setSecurityManager(new SecurityManager());

    test("security");

    LogManager.getLogManager().readConfiguration();

    final JavaAWTAccessStub access = new JavaAWTAccessStub();
    SharedSecrets.setJavaAWTAccess(access);

    test("security and no context");

    for (Context ctx : Context.values()) {

        LogManager.getLogManager().readConfiguration();

        access.setContext(ctx);

        test("security and context " + ctx);
    }
}
 
Example #29
Source File: LogManagerHelper.java    From syslog-java-client with MIT License 5 votes vote down vote up
/**
 * Visible version of {@link java.util.logging.LogManager#getStringProperty(String, String)}.
 *
 * If the property is not defined we return the given default value.
 */
public static String getStringProperty(@Nonnull LogManager manager, @Nullable String name, String defaultValue) {
    if (name == null) {
        return defaultValue;
    }
    String val = manager.getProperty(name);
    if (val == null) {
        return defaultValue;
    }
    return val.trim();
}
 
Example #30
Source File: MASConsoleGUI.java    From jason with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void initMainPanel() {
    String tabbed = LogManager.getLogManager().getProperty(isTabbedPropField);
    if (tabbed != null && tabbed.equals("true")) {
        isTabbed = true;
    }
    pcenter = new JPanel(new BorderLayout());
    if (isTabbed) {
        tabPane = new JTabbedPane(JTabbedPane.LEFT);
        pcenter.add(BorderLayout.CENTER, tabPane);
    }
    frame.getContentPane().add(BorderLayout.CENTER, pcenter);
}