java.util.logging.Filter Java Examples

The following examples show how to use java.util.logging.Filter. 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: PHPTestBase.java    From netbeans with Apache License 2.0 7 votes vote down vote up
private static void suppressUselessLogging() {
    for (Handler handler : Logger.getLogger("").getHandlers()) {
        handler.setFilter(new Filter() {

            @Override
            public boolean isLoggable(LogRecord record) {
                boolean result = true;
                if (record.getSourceClassName().startsWith("org.netbeans.modules.parsing.impl.indexing.LogContext")
                        || record.getSourceClassName().startsWith("org.netbeans.modules.parsing.impl.indexing.RepositoryUpdater")
                        || record.getSourceClassName().startsWith("org.netbeans.modules.editor.settings.storage.keybindings.KeyMapsStorage")
                        || record.getSourceClassName().startsWith("org.netbeans.modules.settings.RecognizeInstanceObjects$OverObjects")) { //NOI18N
                    result = false;
                }
                return result;
            }
        });
    }
}
 
Example #2
Source File: LatteTestBase.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static void suppressUselessLogging() {
    for (Handler handler : Logger.getLogger("").getHandlers()) {
        handler.setFilter(new Filter() {

            @Override
            public boolean isLoggable(LogRecord record) {
                boolean result = true;
                if (record.getSourceClassName().startsWith("org.netbeans.modules.parsing.impl.indexing.LogContext")
                        || record.getSourceClassName().startsWith("org.netbeans.modules.parsing.impl.indexing.RepositoryUpdater")
                        || record.getSourceClassName().startsWith("org.netbeans.modules.editor.settings.storage.keybindings.KeyMapsStorage")) { //NOI18N
                    result = false;
                }
                return result;
            }
        });
    }
}
 
Example #3
Source File: LogWrapper.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
private LogWrapper() {
  logger = Logger.getLogger(this.getClass().getCanonicalName());

  Cache cache = CliUtil.getCacheIfExists();
  if (cache != null && !cache.isClosed()) {
    //TODO - Abhishek how to set different log levels for different handlers???
    logger.addHandler(cache.getLogger().getHandler());
    CommandResponseWriterHandler handler = new CommandResponseWriterHandler();
    handler.setFilter(new Filter() {
      @Override
      public boolean isLoggable(LogRecord record) {
        return record.getLevel().intValue() >= Level.FINE.intValue();
      }
    });
    handler.setLevel(Level.FINE);
    logger.addHandler(handler);
  }
  logger.setUseParentHandlers(false);
}
 
Example #4
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 #5
Source File: LogWrapper.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
private LogWrapper() {
  logger = Logger.getLogger(this.getClass().getCanonicalName());

  Cache cache = CliUtil.getCacheIfExists();
  if (cache != null && !cache.isClosed()) {
    //TODO - Abhishek how to set different log levels for different handlers???
    logger.addHandler(cache.getLogger().getHandler());
    CommandResponseWriterHandler handler = new CommandResponseWriterHandler();
    handler.setFilter(new Filter() {
      @Override
      public boolean isLoggable(LogRecord record) {
        return record.getLevel().intValue() >= Level.FINE.intValue();
      }
    });
    handler.setLevel(Level.FINE);
    logger.addHandler(handler);
  }
  logger.setUseParentHandlers(false);
}
 
Example #6
Source File: TwigTestBase.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static void suppressUselessLogging() {
    for (Handler handler : Logger.getLogger("").getHandlers()) {
        handler.setFilter(new Filter() {

            @Override
            public boolean isLoggable(LogRecord record) {
                boolean result = true;
                if (record.getSourceClassName().startsWith("org.netbeans.modules.parsing.impl.indexing.LogContext")
                        || record.getSourceClassName().startsWith("org.netbeans.modules.parsing.impl.indexing.RepositoryUpdater")
                        || record.getSourceClassName().startsWith("org.netbeans.modules.editor.settings.storage.keybindings.KeyMapsStorage")) { //NOI18N
                    result = false;
                }
                return result;
            }
        });
    }
}
 
Example #7
Source File: RefactoringTestBase.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static void suppressUselessLogging() {
    for (Handler handler : Logger.getLogger("").getHandlers()) {
        handler.setFilter(new Filter() {

            @Override
            public boolean isLoggable(LogRecord record) {
                boolean result = true;
                if (record.getSourceClassName().startsWith("org.netbeans.modules.parsing.impl.indexing.LogContext")
                        || record.getSourceClassName().startsWith("org.netbeans.modules.parsing.impl.indexing.RepositoryUpdater")
                        || record.getSourceClassName().startsWith("org.netbeans.modules.editor.settings.storage.keybindings.KeyMapsStorage")) { //NOI18N
                    result = false;
                }
                return result;
            }
        });
    }
}
 
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: ProtocolNegotiatorsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void engineLog() {
  ChannelHandler handler = new ServerTlsHandler(grpcHandler, sslContext, null);
  pipeline.addLast(handler);
  channelHandlerCtx = pipeline.context(handler);

  Logger logger = Logger.getLogger(ProtocolNegotiators.class.getName());
  Filter oldFilter = logger.getFilter();
  try {
    logger.setFilter(new Filter() {
      @Override
      public boolean isLoggable(LogRecord record) {
        // We still want to the log method to be exercised, just not printed to stderr.
        return false;
      }
    });

    ProtocolNegotiators.logSslEngineDetails(
        Level.INFO, channelHandlerCtx, "message", new Exception("bad"));
  } finally {
    logger.setFilter(oldFilter);
  }
}
 
Example #10
Source File: FileLogHandler.java    From slf4android with MIT License 5 votes vote down vote up
@Override
public void setFilter(Filter newFilter) {
    super.setFilter(newFilter);
    ensureInitialized();
    if (fileHandler != null) {
        fileHandler.setFilter(newFilter);
    }
}
 
Example #11
Source File: LogUtils.java    From BetonQuest with GNU General Public License v3.0 5 votes vote down vote up
private static Filter getLogFilter() {
    return (record) -> {
        if (debugging) {
            return true;
        }
        History.logToHistory(record);
        return false;
    };
}
 
Example #12
Source File: LocalSpawnRunnerTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Before
public final void suppressLogging() {
  logger = Logger.getLogger(TestedLocalSpawnRunner.class.getName());
  logger.setFilter(new Filter() {
    @Override
    public boolean isLoggable(LogRecord record) {
      return false;
    }
  });
}
 
Example #13
Source File: ProtocolNegotiatorsTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void engineLog() {
  ChannelHandler handler = new ServerTlsHandler(sslContext, grpcHandler);
  pipeline.addLast(handler);
  channelHandlerCtx = pipeline.context(handler);

  Logger logger = Logger.getLogger(ProtocolNegotiators.class.getName());
  Filter oldFilter = logger.getFilter();
  try {
    logger.setFilter(new Filter() {
      @Override
      public boolean isLoggable(LogRecord record) {
        // We still want to the log method to be exercised, just not printed to stderr.
        return false;
      }
    });

    ProtocolNegotiators.logSslEngineDetails(
        Level.INFO, channelHandlerCtx, "message", new Exception("bad"));
  } finally {
    logger.setFilter(oldFilter);
  }
}
 
Example #14
Source File: EngineLogger.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private void publishToLogger( Logger logger, LogRecord record )
{
	if ( !logger.isLoggable( record.getLevel( ) ) )
	{
		return;
	}
	synchronized ( logger )
	{
		Filter filter = logger.getFilter( );
		if ( filter != null && !filter.isLoggable( record ) )
		{
			return;
		}
	}
	// Post the LogRecord to all our Handlers, and then to
	// our parents' handlers, all the way up the tree.

	while ( logger != null )
	{
		Handler targets[] = logger.getHandlers( );

		if ( targets != null )
		{
			for ( int i = 0; i < targets.length; i++ )
			{
				targets[i].publish( record );
			}
		}

		if ( !logger.getUseParentHandlers( ) )
		{
			break;
		}

		logger = logger.getParent( );
	}
}
 
Example #15
Source File: AbstractDelegatingLogger.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void internalLog(LogRecord record) {
    Filter filter = getFilter();
    if (filter != null && !filter.isLoggable(record)) {
        return;
    }
    String msg = formatMessage(record);
    internalLogFormatted(msg, record);
}
 
Example #16
Source File: MavenLogHandler.java    From jaxb2-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves a java.util.Logging filter used to ensure that only LogRecords whose
 * logger names start with any of the required prefixes are logged.
 *
 * @param requiredPrefixes A non-null list of prefixes to be matched with the LogRecord logger names.
 * @return A java.util.logging Filter that only permits logging LogRecords whose
 * logger names start with any of the required prefixes.
 */
public static Filter getLoggingFilter(final String... requiredPrefixes) {

    // Check sanity
    Validate.notNull(requiredPrefixes, "requiredPrefixes");

    // All done.
    return new Filter() {

        // Internal state
        private List<String> requiredPrefs = Arrays.asList(requiredPrefixes);

        @Override
        public boolean isLoggable(final LogRecord record) {

            final String loggerName = record.getLoggerName();
            for (String current : requiredPrefs) {
                if (loggerName.startsWith(current)) {
                    return true;
                }
            }

            // No matches found.
            return false;
        }
    };
}
 
Example #17
Source File: ConsoleHandlerTest.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
@Test
void shouldNotAppendMessageToConsoleWhenRecordIsNotLoggable(@Mock final Filter filter) {
  when(filter.isLoggable(record)).thenReturn(false);
  consoleHandler.setFilter(filter);

  consoleHandler.publish(record);

  verify(console, never()).append(anyString());
}
 
Example #18
Source File: ErrorMessageHandlerTest.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
@Test
void shouldNotInvokeConsumerWhenRecordIsNotLoggable(@Mock final Filter filter) {
  final LogRecord record = newLogRecord(ErrorMessageHandler.THRESHOLD_LEVEL_VALUE);
  when(filter.isLoggable(record)).thenReturn(false);
  errorMessageHandler.setFilter(filter);

  errorMessageHandler.publish(record, consumer);

  verify(consumer, never()).accept(any());
}
 
Example #19
Source File: AbstractDelegatingLogger.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
protected void internalLog(LogRecord record) {
    Filter filter = getFilter();
    if (filter != null && !filter.isLoggable(record)) {
        return;
    }
    String msg = formatMessage(record);
    internalLogFormatted(msg, record);
}
 
Example #20
Source File: MetadataSource.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Reports a warning.
 *
 * @param source  the source class, either {@code MetadataSource} or {@code MetadataWriter}.
 * @param method  the method to report as the warning emitter.
 * @param record  the warning to report.
 */
final void warning(final Class<? extends MetadataSource> source, final String method, final LogRecord record) {
    record.setSourceClassName(source.getCanonicalName());
    record.setSourceMethodName(method);
    record.setLoggerName(Loggers.SQL);
    final Filter filter = logFilter;
    if (filter == null || filter.isLoggable(record)) {
        CachedStatement.LOGGER.log(record);
    }
}
 
Example #21
Source File: VespaClientBuilderFactory.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static void disableConfigLogging(String className) {
    @SuppressWarnings("LoggerInitializedWithForeignClass")
    Logger logger = Logger.getLogger(className);
    Optional<Filter> currentFilter = Optional.ofNullable(logger.getFilter());
    Filter filter = logRecord ->
            !logRecord.getMessage().startsWith("Restricted headers are not enabled")
                    && !logRecord.getMessage().startsWith("Selected ExecutorServiceProvider implementation")
                    && !logRecord.getLevel().equals(CONFIG)
                    && currentFilter.map(f -> f.isLoggable(logRecord)).orElse(true); // Honour existing filter if exists
    logger.setFilter(filter);
}
 
Example #22
Source File: LogHandlerBase.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Publishes the record.
 */
@Override
public final void publish(LogRecord record)
{
  if (! isLoggable(record)) {
    return;
  }

  Filter filter = getFilter();

  if (filter != null && ! filter.isLoggable(record))
    return;

  if (record == null) {
    System.out.println(this + ": no record");
    return;
  }

  //synchronized (this) {
    processPublish(record);
    //processFlush();
  //}

  /*
  _logQueue.offer(record);

  if (CurrentTime.isTest()) {
    waitForEmpty();
  }
  */
}
 
Example #23
Source File: AbstractDelegatingLogger.java    From tomee with Apache License 2.0 5 votes vote down vote up
protected void internalLog(final LogRecord record) {
    final Filter filter = getFilter();
    if (filter != null && !filter.isLoggable(record)) {
        return;
    }
    final String msg = formatMessage(record);
    internalLogFormatted(msg, record);
}
 
Example #24
Source File: HandlersConfigTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void check(MemoryHandler handler,
           Level expectedLevel,
           String expectedEncoding,
           Class<? extends Filter> expectedFilterType,
           Class<? extends Formatter> expectedFormatterType,
           Class<? extends Handler> expextedTargetType,
           int expextedSize,
           Level expectedPushLevel) {
    checkType(handler, "target", getTarget(handler), expextedTargetType);
    checkEquals(handler, "size", getSize(handler), expextedSize);
    checkEquals(handler, "pushLevel", handler.getPushLevel(), expectedPushLevel);
    check(handler, expectedLevel, expectedEncoding, expectedFilterType, expectedFormatterType);
}
 
Example #25
Source File: PerfMarkTest.java    From perfmark with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Exception {
  Class<?> implClz = Class.forName("io.perfmark.impl.SecretPerfMarkImpl$PerfMarkImpl");
  Field propertyField = implClz.getDeclaredField("START_ENABLED_PROPERTY");
  propertyField.setAccessible(true);
  String startEnabledProperty = (String) propertyField.get(null);
  Logger logger = Logger.getLogger(PerfMark.class.getName());
  Filter oldFilter = logger.getFilter();
  // This causes a cycle in case PerfMark tries to log during init.
  // Also, it silences initial nagging about missing generators.
  logger.setFilter(
      new Filter() {
        @Override
        public boolean isLoggable(LogRecord record) {
          PerfMark.startTask("isLoggable");
          try {
            return false;
          } finally {
            PerfMark.stopTask("isLoggable");
          }
        }
      });
  // Try to get PerfMark to accidentally log that it is enabled.  We are careful to not
  // accidentally cause class initialization early here, as START_ENABLED_PROPERTY is a
  // constant.
  String oldProperty = System.getProperty(startEnabledProperty);
  System.setProperty(startEnabledProperty, "true");
  try {
    Class.forName(PerfMark.class.getName());
  } finally {
    if (oldProperty == null) {
      System.clearProperty(startEnabledProperty);
    } else {
      System.setProperty(startEnabledProperty, oldProperty);
    }
    logger.setFilter(oldFilter);
  }
}
 
Example #26
Source File: AbstractBackend.java    From flogger with Apache License 2.0 5 votes vote down vote up
void log(LogRecord record, boolean wasForced) {
  // Do the fast boolean check (which normally succeeds) before calling isLoggable().
  if (!wasForced || logger.isLoggable(record.getLevel())) {
    // Unforced log statements or forced log statements at or above the logger's level can be
    // passed to the normal log(LogRecord) method.
    logger.log(record);
  } else {
    // If logging has been forced for a log record which would otherwise be discarded, we cannot
    // call our logger's log(LogRecord) method, so we must simulate its behavior in one of two
    // ways.
    // 1: Simulate the effect of calling the log(LogRecord) method directly (this is safe if the
    //    logger provided by the log manager was a normal Logger instance).
    // 2: Obtain a "child" logger from the log manager which is set to log everything, and call
    //    its log(LogRecord) method instead (which should have the same overridden behavior and
    //    will still publish log records to our logger's handlers).
    //
    // In all cases we still call the filter (if one exists) even though we ignore the result.
    // Use a local variable to avoid race conditions where the filter can be unset at any time.
    Filter filter = logger.getFilter();
    if (filter != null) {
      filter.isLoggable(record);
    }
    if (logger.getClass() == Logger.class || cannotUseForcingLogger) {
      // If the Logger instance is not a subclass, its log(LogRecord) method cannot have been
      // overridden. That means it's safe to just publish the log record directly to handlers
      // to avoid the loggability check, which would otherwise discard the forced log record.
      publish(logger, record);
    } else {
      // Hopefully rare situation in which the logger is subclassed _and_ the log record would
      // normally be discarded based on its level.
      forceLoggingViaChildLogger(record);
    }
  }
}
 
Example #27
Source File: ModelIndexTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();
    FileObject f = FileUtil.getConfigFile(FOLDER + "/text/html");

    if (f != null) {
        f.delete();
    }

    Logger.global.setFilter(new Filter() {

        public boolean isLoggable(LogRecord record) {
            Throwable t = record.getThrown();

            if (t == null) {
                return true;
            }

            for (StackTraceElement e : t.getStackTrace()) {
                if ("org.netbeans.modules.php.editor.index.GsfUtilities".equals(e.getClassName()) && "getBaseDocument".equals(e.getMethodName()) && t instanceof ClassNotFoundException) {
                    return false;
                }
            }
            return false;
        }
    });
}
 
Example #28
Source File: PHPNavTestBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();
    TestLanguageProvider.register(getPreferredLanguage().getLexerLanguage());
    FileObject f = FileUtil.getConfigFile(FOLDER + "/text/html");

    if (f != null) {
        f.delete();
    }

    Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).setFilter(new Filter() {
        @Override
        public boolean isLoggable(LogRecord record) {
            Throwable t = record.getThrown();

            if (t == null) {
                return true;
            }

            for (StackTraceElement e : t.getStackTrace()) {
                if (   "org.netbeans.modules.php.editor.index.GsfUtilities".equals(e.getClassName())
                    && "getBaseDocument".equals(e.getMethodName())
                    && t instanceof ClassNotFoundException) {
                    return false;
                }
            }
            return false;
        }
    });
}
 
Example #29
Source File: Util.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Disable logging of logging messages from DatabaseUILogger. See #215375.
 *
 * Usefulness of the whole logger seems to be doubtful
 */
public static void suppressSuperfluousLogging() {
    for (Handler h : Logger.getLogger("").getHandlers()) {
        h.setFilter(new Filter() {
            @Override
            public boolean isLoggable(LogRecord lr) {
                if (lr.getSourceClassName().equals("org.netbeans.modules.db.explorer.DatabaseUILogger")
                        || lr.getSourceClassName().startsWith("org.netbeans.modules.settings.RecognizeInstanceObjects")) {
                    return false;
                } else if (lr.getSourceClassName().equals(
                        "org.netbeans.api.db.sql.support.SQLIdentifiers$DatabaseMetaDataQuoter")) {
                    if (lr.getSourceMethodName().equals("getExtraNameChars")
                            && lr.getLevel() == Level.WARNING
                            && lr.getMessage().startsWith(
                                    "DatabaseMetaData.getExtraNameCharacters() failed")) {
                        return false;
                    } else if (lr.getSourceMethodName().equals("needToQuote")
                            && lr.getLevel().intValue()
                            <= Level.INFO.intValue()) {
                        return false;
                    } else {
                        return true;
                    }
                } else if (lr.getSourceClassName().equals(
                        "org.netbeans.modules.db.explorer.DatabaseConnection") &&
                        lr.getSourceMethodName().equals("doConnect")) {
                    return false;
                } else {
                    return true;
                }
            }
        });
    }
}
 
Example #30
Source File: DBTestUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Disable logging of logging messages from DatabaseMetaDataQuoter.
 *
 * This method is a workaround of problems in the database modules and can
 * be removed, when the problem is really fixed.
 *
 */
public static void suppressSuperfluousLogging() {
    // TODO: Remove this code and fix the core problem
    for (Handler h : Logger.getLogger("").getHandlers()) {
        h.setFilter(new Filter() {
            @Override
            public boolean isLoggable(LogRecord lr) {
                if (lr.getSourceClassName().equals(
                        "org.netbeans.api.db.sql.support.SQLIdentifiers$DatabaseMetaDataQuoter")) {
                    if (lr.getSourceMethodName().equals("getExtraNameChars")
                            && lr.getLevel() == Level.WARNING
                            && lr.getMessage().startsWith(
                            "DatabaseMetaData.getExtraNameCharacters() failed")) {
                        return false;
                    } else if (lr.getSourceMethodName().equals("needToQuote")
                            && lr.getLevel().intValue() <= Level.INFO.intValue()) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    return true;
                }
            }
        });
    }
}