Java Code Examples for java.util.logging.Logger#setUseParentHandlers()

The following examples show how to use java.util.logging.Logger#setUseParentHandlers() . 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: ClientTest.java    From java-asana with MIT License 6 votes vote down vote up
@Test
public void testAsanaChangeLogging() throws IOException
{
    Logger logger = Logger.getLogger(Request.class.getCanonicalName());
    LogHandler handler = new LogHandler();
    handler.setLevel(Level.ALL);
    logger.setUseParentHandlers(false);
    logger.addHandler(handler);
    logger.setLevel(Level.ALL);

    String req = "{ \"data\": [ { \"gid\": 1 }],\"next_page\": {\"offset\": \"b\",\"path\": \"/tasks?project=1&limit=5&offset=b\",\"uri\": \"https://app.asana.com/api/1.0/tasks?project=1&limit=5&offset=b\"}}";
    dispatcher.registerResponse("GET", "http://app/projects/1/tasks?limit=5&offset=a").code(200).content(req)
            .header("asana-change","name=string_ids;info=something;affected=true")
            .header("asana-change", "name=new_sections;info=something;affected=true");

    client.tasks.findByProject("1")
            .option("limit", 5).option("offset", "a")
            .executeRaw();

    assertEquals("Log level as expected?", Level.WARNING, handler.checkLevel() );
}
 
Example 2
Source File: Ideas_2009_05_06.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * The logger reference is lost at the end of the method (it doesn't escape
 * the method), so if you have a garbage collection cycle just after the
 * call to initLogging, the logger configuration is lost (because Logger
 * only keeps weak references).
 */

@ExpectWarning("LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE")
public static void initLogging() throws SecurityException, IOException {
    Logger logger = Logger.getLogger("edu.umd.cs.findbugs");
    logger.addHandler(new FileHandler()); // call to change logger
                                          // configuration
    logger.setUseParentHandlers(false); // another call to change logger
                                        // configuration
    logger.setLevel(Level.FINER);
    logger.setFilter(new Filter() {

        @Override
        public boolean isLoggable(LogRecord arg0) {
            return true;
        }
    });
}
 
Example 3
Source File: Installer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void preferenceChange(PreferenceChangeEvent evt) {
    if (corePref.equals(evt.getNode()) && USAGE_STATISTICS_ENABLED.equals(evt.getKey())) {
        boolean newVal = Boolean.parseBoolean(evt.getNewValue());
        if (newVal != logMetricsEnabled) {
            corePref.putBoolean(USAGE_STATISTICS_SET_BY_IDE, true);
            logMetricsEnabled = newVal;
            Logger log = Logger.getLogger(METRICS_LOGGER_NAME);
            if (logMetricsEnabled) {
                log.setUseParentHandlers(true);
                log.setLevel(Level.FINEST);
                log.addHandler(metrics);
                MetricsHandler.setFlushOnRecord(false);
            } else {
                MetricsHandler.flushImmediatelly();
                closeLogStreamMetrics();
                log.removeHandler(metrics);
            }
        }
    }
}
 
Example 4
Source File: CounterGroupTestCase.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasic() {
    Logger logger = Logger.getLogger(CounterGroup.class.getName());
    boolean initUseParentHandlers = logger.getUseParentHandlers();
    Handler logChecker = new CounterGroupHandler();
    logger.setUseParentHandlers(false);
    CounterGroup c = new CounterGroup("test", Statistics.nullImplementation, false);
    Counter n;
    c.increment("a");
    c.increment("b");
    c.increment("a", 499);
    n = c.getCounter("a");
    assertEquals(500, n.get());
    n = c.getCounter("b");
    assertEquals(1, n.get());
    n = c.getCounter("c");
    assertEquals(0, n.get());
    logger.addHandler(logChecker);
    c.run();
    assertFalse("The logging handler did not really run.", gotRecord == false);
    // cleanup:
    logger.removeHandler(logChecker);
    logger.setUseParentHandlers(initUseParentHandlers);
}
 
Example 5
Source File: ClientSharedUtils.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public static void initLogger(String loggerName, String logFile,
    boolean initLog4j, Level level, final Handler handler) {
  clearLogger();
  if (initLog4j) {
    try {
      initLog4J(logFile, level);
    } catch (IOException ioe) {
      throw newRuntimeException(ioe.getMessage(), ioe);
    }
  }
  Logger log = Logger.getLogger(loggerName);
  log.addHandler(handler);
  log.setLevel(level);
  log.setUseParentHandlers(false);
  logger = log;
}
 
Example 6
Source File: JdbcThinPartitionAwarenessReconnectionAndFailoverSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
    super.beforeTestsStarted();

    startGridsMultiThreaded(INITIAL_NODES_CNT);

    Logger log = Logger.getLogger(JdbcThinConnection.class.getName());
    logHnd = new LogHandler();
    logHnd.setLevel(Level.ALL);
    log.setUseParentHandlers(false);
    log.addHandler(logHnd);
    log.setLevel(Level.ALL);
}
 
Example 7
Source File: StampsTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    branding = NbBundle.getBranding();
    locale = Locale.getDefault();
    
    clearWorkDir();
    
    install = new File(getWorkDir(), "install");
    platform = new File(install, "platform");
    ide = createIdeCluster(install);
    userdir = new File(getWorkDir(), "tmp");
    
    System.setProperty("netbeans.home", platform.getPath());
    System.setProperty("netbeans.dirs", ide.getPath());
    System.setProperty("netbeans.user", userdir.getPath());
    
    createModule("org.openide.awt", platform, 50000L);
    createModule("org.openide.nodes", platform, 60000L);
    createModule("org.netbeans.api.languages", ide, 90000L);
    createModule("org.netbeans.modules.logmanagement", userdir, 10000L);
    
    reset();
    
    Thread.sleep(100);

    Logger l = Logger.getLogger("org");
    l.setLevel(Level.OFF);
    l.setUseParentHandlers(false);
}
 
Example 8
Source File: GoogleLoggerTest.java    From flogger with Apache License 2.0 5 votes vote down vote up
@Before
public void addAssertingHandler() {
  logger = GoogleLogger.forEnclosingClass();
  assertingHandler = new AssertingHandler();
  assertingHandler.setLevel(Level.INFO);
  Logger jdkLogger = Logger.getLogger(GoogleLoggerTest.class.getName());
  jdkLogger.setUseParentHandlers(false);
  jdkLogger.addHandler(assertingHandler);
  jdkLogger.setLevel(Level.INFO);
}
 
Example 9
Source File: Recorder.java    From SikuliX1 with MIT License 5 votes vote down vote up
private static void registerNativeHook() {
  try {
    // Make Global Screen logger quiet.
    // Floods the console otherwise
    Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
    logger.setLevel(Level.OFF);
    logger.setUseParentHandlers(false);

    GlobalScreen.registerNativeHook();
  } catch (NativeHookException e) {
    Debug.error("Error registering native hook: %s", e.getMessage());
  }
}
 
Example 10
Source File: EngineLoggerTest.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * the user uses the user defined log. All log should be outputted to the
 * user defined logger.
 * 
 * @throws Exception
 */
public void testUserLogger( ) throws Exception
{
	// init the root logger
	FileHandler fileHandle = new FileHandler( "./utest/logger.txt" );
	try
	{
		Logger logger = Logger.getAnonymousLogger( );
		logger.addHandler( fileHandle );
		logger.setLevel( Level.ALL );
		logger.setUseParentHandlers( false );
		try
		{

			// start a default logger
			LoggerSetting setting = EngineLogger.createSetting(logger, null, null, Level.FINE, 0, 0);

			// all the log should be output to the root logger
			log( );
			EngineLogger.setLogger( setting, null );
			log( );
			EngineLogger.removeSetting(setting);
		}
		finally
		{
			logger.removeHandler( fileHandle );
		}
	}
	finally
	{
		fileHandle.close( );
	}
	// test the log file content
	checkLogging( "./utest/logger.txt", 0, 1, 1 );
}
 
Example 11
Source File: ScanMonitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private ScanMonitor() {
    Logger logger = Logger.getLogger("org.netbeans.modules.java.source.usages.RepositoryUpdater.activity"); //NOI18N
    logger.setLevel(Level.FINEST);
    logger.setUseParentHandlers(false);
    logger.addHandler( new Handler() { //NOI18N

        @Override
        public void publish(LogRecord record) {
            if( Level.FINEST.equals( record.getLevel() )
                    && "START".equals(record.getMessage()) ) { //NOI18N
                lock();
                return;
            }

            if( Level.FINEST.equals( record.getLevel() )
                    && "FINISHED".equals(record.getMessage()) ) { //NOI18N
                unlock();
                return;
            }
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    });
}
 
Example 12
Source File: Logging.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static Logger instantiateLogger(final String name, final Level level) {
    final Logger logger = java.util.logging.Logger.getLogger(name);
    for (final Handler h : logger.getHandlers()) {
        logger.removeHandler(h);
    }

    logger.setLevel(level);
    logger.setUseParentHandlers(false);
    final Handler c = new ConsoleHandler();

    c.setFormatter(new Formatter() {
        @Override
        public String format(final LogRecord record) {
            final StringBuilder sb = new StringBuilder();

            sb.append('[')
               .append(record.getLoggerName())
               .append("] ")
               .append(record.getMessage())
               .append('\n');

            return sb.toString();
        }
    });
    logger.addHandler(c);
    c.setLevel(level);

    return logger;
}
 
Example 13
Source File: RoboconfConsumerTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleDeliveryWithDeserializationError() throws Exception {

	RoboconfMessageQueue messageQueue = new RoboconfMessageQueue();
	Channel channel = Mockito.mock( Channel.class );
	RoboconfConsumer rc = new RoboconfConsumer( "DM", channel, messageQueue );

	final StringHandler logHandler = new StringHandler();
	Logger logger = TestUtils.getInternalField( rc, "logger", Logger.class );
	logger.setUseParentHandlers( false );
	logger.addHandler( logHandler );

	rc.handleDelivery( "tag", Mockito.mock( Envelope.class ), null, new byte[ 1 ]);
	Assert.assertTrue( logHandler.getLogs().startsWith( "DM: a message could not be deserialized." ));
}
 
Example 14
Source File: GitClientCliCloneTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Before
public void setUpRepositories() throws Exception {
    Logger logger = Logger.getLogger(this.getClass().getPackage().getName() + "-" + random.nextInt());
    handler = new LogHandler();
    handler.setLevel(Level.ALL);
    logger.setUseParentHandlers(false);
    logger.addHandler(handler);
    logger.setLevel(Level.ALL);
    listener = new hudson.util.LogTaskListener(logger, Level.ALL);

    workspace = new WorkspaceWithRepo(repo.getRoot(), "git", listener); // Tests explicitly check CLI git only
    testGitClient = workspace.getGitClient();
}
 
Example 15
Source File: TestLoggingConfigurer.java    From scriptella-etl with Apache License 2.0 5 votes vote down vote up
public void tearDown() {
    if (handler != null) {
        final Logger logger = Logger.getLogger(loggerName);
        logger.setUseParentHandlers(oldUseParent);
        logger.removeHandler(handler);
        handler = null;
    }
}
 
Example 16
Source File: ClassLoaderLogManager.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Add the specified logger to the classloader local configuration.
 *
 * @param logger The logger to be added
 */
@Override
public synchronized boolean addLogger(final Logger logger) {

    final String loggerName = logger.getName();

    ClassLoader classLoader =
        Thread.currentThread().getContextClassLoader();
    ClassLoaderLogInfo info = getClassLoaderInfo(classLoader);
    if (info.loggers.containsKey(loggerName)) {
        return false;
    }
    info.loggers.put(loggerName, logger);

    // Apply initial level for new logger
    final String levelString = getProperty(loggerName + ".level");
    if (levelString != null) {
        try {
            AccessController.doPrivileged(new PrivilegedAction<Void>() {
                @Override
                public Void run() {
                    logger.setLevel(Level.parse(levelString.trim()));
                    return null;
                }
            });
        } catch (IllegalArgumentException e) {
            // Leave level set to null
        }
    }

    // Always instantiate parent loggers so that
    // we can control log categories even during runtime
    int dotIndex = loggerName.lastIndexOf('.');
    if (dotIndex >= 0) {
        final String parentName = loggerName.substring(0, dotIndex);
        Logger.getLogger(parentName);
    }

    // Find associated node
    LogNode node = info.rootNode.findNode(loggerName);
    node.logger = logger;

    // Set parent logger
    Logger parentLogger = node.findParentLogger();
    if (parentLogger != null) {
        doSetParentLogger(logger, parentLogger);
    }

    // Tell children we are their new parent
    node.setParentLogger(logger);

    // Add associated handlers, if any are defined using the .handlers property.
    // In this case, handlers of the parent logger(s) will not be used
    String handlers = getProperty(loggerName + ".handlers");
    if (handlers != null) {
        logger.setUseParentHandlers(false);
        StringTokenizer tok = new StringTokenizer(handlers, ",");
        while (tok.hasMoreTokens()) {
            String handlerName = (tok.nextToken().trim());
            Handler handler = null;
            ClassLoader current = classLoader;
            while (current != null) {
                info = classLoaderLoggers.get(current);
                if (info != null) {
                    handler = info.handlers.get(handlerName);
                    if (handler != null) {
                        break;
                    }
                }
                current = current.getParent();
            }
            if (handler != null) {
                logger.addHandler(handler);
            }
        }
    }

    // Parse useParentHandlers to set if the logger should delegate to its parent.
    // Unlike java.util.logging, the default is to not delegate if a list of handlers
    // has been specified for the logger.
    String useParentHandlersString = getProperty(loggerName + ".useParentHandlers");
    if (Boolean.parseBoolean(useParentHandlersString)) {
        logger.setUseParentHandlers(true);
    }

    return true;
}
 
Example 17
Source File: StampsExtraTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testTimeStampsWhenAddingCluster() throws Exception {
    clearWorkDir();
    
    install = new File(getWorkDir(), "install");
    platform = new File(install, "platform");
    platform.mkdirs();
    ide = new File(install, "ide");
    ide.mkdirs();
    extra = new File(install, "extra");
    userdir = new File(getWorkDir(), "tmp");
    userdir.mkdirs();
    
    System.setProperty("netbeans.home", platform.getPath());
    System.setProperty("netbeans.dirs", ide.getPath() + File.pathSeparator + extra.getPath());
    PlacesTestUtils.setUserDirectory(userdir);

    touch(platform, ".lastModified", 50000L);
    touch(ide, ".lastModified", 90000L);
    assertFalse("One cluster does not exists", extra.isDirectory());
    
    Stamps.main("init");
    
    Thread.sleep(100);

    Logger l = Logger.getLogger("org");
    l.setLevel(Level.OFF);
    l.setUseParentHandlers(false);

    long stamp = Stamps.moduleJARs();
    assertEquals("Timestamp is taken from api.languages module", 90000L, stamp);

    Stamps.main("clear");

    CountingSecurityManager.initialize(install.getPath());

    long newStamp = Stamps.moduleJARs();

    CountingSecurityManager.assertCounts("Just few accesses to installation", 6);
    assertEquals("Stamps are the same", stamp, newStamp);

    assertFalse("File has not been created for non-existing cluster", Places.getCacheSubfile("lastModified/extra").canRead());

    extra.mkdirs();
    File lastModified = new File(extra, ".lastModified");
    lastModified.createNewFile();
    lastModified.setLastModified(200000L);
    assertEquals("Correct last modified", 200000L, lastModified.lastModified());

    Stamps.main("clear");
    stamp = Stamps.moduleJARs();
    if (stamp < 200000L) {
        fail("lastModified has not been updated: " + stamp);
    }
}
 
Example 18
Source File: TestAnonymousLogger.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) {
    System.setSecurityManager(new SecurityManager());
    Logger anonymous = Logger.getAnonymousLogger();

    final TestHandler handler = new TestHandler();
    final TestFilter filter = new TestFilter();
    final ResourceBundle bundle = ResourceBundle.getBundle(TestBundle.class.getName());
    anonymous.setLevel(Level.FINEST);
    anonymous.addHandler(handler);
    anonymous.setFilter(filter);
    anonymous.setUseParentHandlers(true);
    anonymous.setResourceBundle(bundle);

    if (anonymous.getLevel() != Level.FINEST) {
        throw new RuntimeException("Unexpected level: " + anonymous.getLevel());
    } else {
        System.out.println("Got expected level: " + anonymous.getLevel());
    }
    if (!Arrays.asList(anonymous.getHandlers()).contains(handler)) {
        throw new RuntimeException("Expected handler not found in: "
                + Arrays.asList(anonymous.getHandlers()));
    } else {
        System.out.println("Got expected handler in: " + Arrays.asList(anonymous.getHandlers()));
    }
    if (anonymous.getFilter() != filter) {
        throw new RuntimeException("Unexpected filter: " + anonymous.getFilter());
    } else {
        System.out.println("Got expected filter: " + anonymous.getFilter());
    }
    if (!anonymous.getUseParentHandlers()) {
        throw new RuntimeException("Unexpected flag: " + anonymous.getUseParentHandlers());
    } else {
        System.out.println("Got expected flag: " + anonymous.getUseParentHandlers());
    }
    if (anonymous.getResourceBundle() != bundle) {
        throw new RuntimeException("Unexpected bundle: " + anonymous.getResourceBundle());
    } else {
        System.out.println("Got expected bundle: " + anonymous.getResourceBundle());
    }
    try {
        anonymous.setParent(Logger.getLogger("foo.bar"));
        throw new RuntimeException("Expected SecurityException not raised!");
    } catch (SecurityException x) {
        System.out.println("Got expected exception: " + x);
    }
    if (anonymous.getParent() != Logger.getLogger("")) {
        throw new RuntimeException("Unexpected parent: " + anonymous.getParent());
    } else {
        System.out.println("Got expected parent: " + anonymous.getParent());
    }
}
 
Example 19
Source File: LogUtil.java    From darklaf with MIT License 4 votes vote down vote up
public static Logger getLogger(final Class<?> clazz) {
    Logger logger = Logger.getLogger(clazz.getName());
    logger.setUseParentHandlers(false);
    logger.addHandler(LOG_HANDLER);
    return logger;
}
 
Example 20
Source File: TestAnonymousLogger.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) {
    System.setSecurityManager(new SecurityManager());
    Logger anonymous = Logger.getAnonymousLogger();

    final TestHandler handler = new TestHandler();
    final TestFilter filter = new TestFilter();
    final ResourceBundle bundle = ResourceBundle.getBundle(TestBundle.class.getName());
    anonymous.setLevel(Level.FINEST);
    anonymous.addHandler(handler);
    anonymous.setFilter(filter);
    anonymous.setUseParentHandlers(true);
    anonymous.setResourceBundle(bundle);

    if (anonymous.getLevel() != Level.FINEST) {
        throw new RuntimeException("Unexpected level: " + anonymous.getLevel());
    } else {
        System.out.println("Got expected level: " + anonymous.getLevel());
    }
    if (!Arrays.asList(anonymous.getHandlers()).contains(handler)) {
        throw new RuntimeException("Expected handler not found in: "
                + Arrays.asList(anonymous.getHandlers()));
    } else {
        System.out.println("Got expected handler in: " + Arrays.asList(anonymous.getHandlers()));
    }
    if (anonymous.getFilter() != filter) {
        throw new RuntimeException("Unexpected filter: " + anonymous.getFilter());
    } else {
        System.out.println("Got expected filter: " + anonymous.getFilter());
    }
    if (!anonymous.getUseParentHandlers()) {
        throw new RuntimeException("Unexpected flag: " + anonymous.getUseParentHandlers());
    } else {
        System.out.println("Got expected flag: " + anonymous.getUseParentHandlers());
    }
    if (anonymous.getResourceBundle() != bundle) {
        throw new RuntimeException("Unexpected bundle: " + anonymous.getResourceBundle());
    } else {
        System.out.println("Got expected bundle: " + anonymous.getResourceBundle());
    }
    try {
        anonymous.setParent(Logger.getLogger("foo.bar"));
        throw new RuntimeException("Expected SecurityException not raised!");
    } catch (SecurityException x) {
        System.out.println("Got expected exception: " + x);
    }
    if (anonymous.getParent() != Logger.getLogger("")) {
        throw new RuntimeException("Unexpected parent: " + anonymous.getParent());
    } else {
        System.out.println("Got expected parent: " + anonymous.getParent());
    }
}