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); }
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); }
@Override public Filter inject() { //noinspection StatementWithEmptyBody if (isInjected()) { //we're injected or in the compound //no-op } else if (isCompound()) { //we have a compound, but we're not in it ((CompoundFilter) getLogger().getFilter()).addFilter(this); } else if (getLogger().getFilter() != null) { //uh-oh, previous filter! previousFilter = getLogger().getFilter(); getLogger().setFilter(new CompoundFilter( //create compound getLogger(), Arrays.asList(this, previousFilter) //called in that order )); } else { //we're alone, let the superclass do the work return super.inject(); } return getLogger().getFilter(); }
@Test public void testInject__multiple() throws Exception { Logger logger = Logger.getLogger("testing"); new PropagatingFilterA(logger).inject(); new PropagatingFilterB(logger).inject(); Filter injected = logger.getFilter(); assertThat("filter wrongly matched arbitrary message multiple", injected.isLoggable(rec(ARBITRARY_TEXT)), is(true)); assertThat("filter didn't match ignored message A multiple", injected.isLoggable(rec(IGNORED_BY_A)), is(false)); assertThat("filter didn't match ignored message B multiple", injected.isLoggable(rec(IGNORED_BY_B)), is(false)); }
/** * 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) { 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; }
/** * Test if info message is logged. */ @Test public void testInfo() { Assert.assertEquals(0, logRecords.size()); JavaLogger javaLogger = new JavaLogger(); javaLogger.setFilter(new Filter() { public boolean isLoggable(LogRecord logRecord) { if (logRecord.getLevel().intValue() == Level.INFO.intValue()) { logRecords.add(logRecord); } return false; } }); EASyLoggerFactory.INSTANCE.setLogger(javaLogger); Assert.assertEquals(0, logRecords.size()); logger.info("This is an info message!"); logger.error("This message should not be logged!"); Assert.assertEquals(1, logRecords.size()); Assert.assertEquals("[" + this.getClass().getSimpleName() + "] This is an info message!", logRecords.get(0).getMessage()); }
/** * Test if error message is logged. */ @Test public void testError() { Assert.assertEquals(0, logRecords.size()); JavaLogger javaLogger = new JavaLogger(); javaLogger.setFilter(new Filter() { public boolean isLoggable(LogRecord logRecord) { if (logRecord.getLevel().intValue() == Level.SEVERE.intValue()) { logRecords.add(logRecord); } return false; } }); EASyLoggerFactory.INSTANCE.setLogger(javaLogger); Assert.assertEquals(0, logRecords.size()); logger.error("This is an error message!"); logger.info("This message should not be logged!"); Assert.assertEquals(1, logRecords.size()); Assert.assertEquals("[" + this.getClass().getSimpleName() + "] This is an error message!", logRecords.get(0).getMessage()); }
/** * Test if debug message is logged. */ @Test public void testDebug() { Assert.assertEquals(0, logRecords.size()); JavaLogger javaLogger = new JavaLogger(); javaLogger.setFilter(new Filter() { public boolean isLoggable(LogRecord logRecord) { Level debugLevel = AbstractJavaLogger.DEBUG_LEVEL; if (logRecord.getLevel().intValue() == debugLevel.intValue()) { logRecords.add(logRecord); } return false; } }); EASyLoggerFactory.INSTANCE.setLogger(javaLogger); Assert.assertEquals(0, logRecords.size()); logger.debug("This is an debug message!"); logger.info("This message should not be logged!"); Assert.assertEquals(1, logRecords.size()); Assert.assertEquals("[" + this.getClass().getSimpleName() + "] This is an debug message!", logRecords.get(0).getMessage()); }
/** * Test if warn message is logged. */ @Test public void testWarn() { Assert.assertEquals(0, logRecords.size()); JavaLogger javaLogger = new JavaLogger(); javaLogger.setFilter(new Filter() { public boolean isLoggable(LogRecord logRecord) { if (logRecord.getLevel().intValue() == Level.WARNING.intValue()) { logRecords.add(logRecord); } return false; } }); EASyLoggerFactory.INSTANCE.setLogger(javaLogger); Assert.assertEquals(0, logRecords.size()); logger.warn("This is an warn message!"); logger.info("This message should not be logged!"); Assert.assertEquals(1, logRecords.size()); Assert.assertEquals("[" + this.getClass().getSimpleName() + "] This is an warn message!", logRecords.get(0).getMessage()); }
/** * Test if exception message is logged. */ @Test public void testException() { Assert.assertEquals(0, logRecords.size()); JavaLogger javaLogger = new JavaLogger(); javaLogger.setFilter(new Filter() { public boolean isLoggable(LogRecord logRecord) { Level exceptionLevel = AbstractJavaLogger.EXCEPTION_LEVEL; if (logRecord.getLevel().intValue() == exceptionLevel.intValue()) { logRecords.add(logRecord); } return false; } }); EASyLoggerFactory.INSTANCE.setLogger(javaLogger); Assert.assertEquals(0, logRecords.size()); Exception nullPointerException = new NullPointerException("This is a NPE for testing purposes!"); logger.exception(nullPointerException); logger.info("This message should not be logged!"); Assert.assertEquals(1, logRecords.size()); Assert.assertEquals("[" + this.getClass().getSimpleName() + "] This is a NPE for testing purposes!", logRecords.get(0).getMessage()); }
/** * private method to get a filter property. 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. * * This method was copied from java.util.logging.LogManager, where it is * package private :-( * * @param name The log property name * @param defaultValue The filter if that property is not specified or * unparsable * @return The filter from the property if set and parsable, the * defaultValue otherwise */ @SuppressWarnings("rawtypes") private Filter getFilterProperty(String name, Filter defaultValue) { String val = LogManager.getLogManager().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; }
private static void setupLogging() { Filter filter = new Filter() { private final String packageName = Main.class.getPackage().getName(); @Override public boolean isLoggable(LogRecord record) { //only log messages from this app String name = record.getLoggerName(); return name != null && name.startsWith(packageName); } }; Logger global = Logger.getLogger(""); Arrays.stream(global.getHandlers()).forEach(h -> h.setFilter(filter)); }
private static void setupLogging() { Filter filter = new Filter() { private final String packageName = Main.class.getPackage().getName(); @Override public boolean isLoggable(final LogRecord record) { // only log messages from this app String name = record.getLoggerName(); return name != null && name.startsWith(packageName); } }; Logger global = Logger.getLogger(""); for (Handler handler : global.getHandlers()) { handler.setFilter(filter); } }
@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); } }
/** * 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; } } }); } }
/** * 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; } } }); } }
void check(Handler handler, Level expectedLevel, String expectedEncoding, Class<? extends Filter> expectedFilterType, Class<? extends Formatter> expectedFormatterType) { checkEquals(handler, "level", handler.getLevel(), expectedLevel); checkEquals(handler, "encoding", handler.getEncoding(), expectedEncoding); checkType(handler, "filter", handler.getFilter(), expectedFilterType); checkType(handler, "formatter", handler.getFormatter(), expectedFormatterType); }
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); }
void check(StreamHandler handler, Level expectedLevel, String expectedEncoding, Class<? extends Filter> expectedFilterType, Class<? extends Formatter> expectedFormatterType, OutputStream expectedOutputStream) { checkEquals(handler, "outputStream", getOutput(handler), expectedOutputStream); check(handler, expectedLevel, expectedEncoding, expectedFilterType, expectedFormatterType); }
/** * 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(); } */ }
@Override public boolean isLoggable(final @Nullable LogRecord record) { if (oldFilter != null && !oldFilter.isLoggable(record)) return false; for (final Filter f : filters) if (!f.isLoggable(record)) return false; return true; }
public void testClose() { Filter filter = handler.getFilter(); Formatter formatter = handler.getFormatter(); writer.getBuffer().setLength(0); handler.close(); assertEquals(writer.toString(), "close"); assertEquals(handler.getFilter(), filter); assertEquals(handler.getFormatter(), formatter); assertNull(handler.getEncoding()); assertNotNull(handler.getErrorManager()); assertEquals(handler.getLevel(), Level.OFF); assertEquals(handler.getPushLevel(), Level.WARNING); assertFalse(handler.isLoggable(new LogRecord(Level.SEVERE, "test"))); }
public void testFlush() { Filter filter = handler.getFilter(); Formatter formatter = handler.getFormatter(); writer.getBuffer().setLength(0); handler.flush(); assertEquals(writer.toString(), "flush"); assertEquals(handler.getFilter(), filter); assertEquals(handler.getFormatter(), formatter); assertNull(handler.getEncoding()); assertNotNull(handler.getErrorManager()); assertEquals(handler.getLevel(), Level.FINE); assertEquals(handler.getPushLevel(), Level.WARNING); assertTrue(handler.isLoggable(new LogRecord(Level.SEVERE, "test"))); }
public void testGetSetFilter_NamedLoggerSufficientPrivilege() { Logger log = Logger .getLogger("testGetSetFilter_NamedLoggerSufficientPrivilege"); Filter f = new MockFilter(); assertNull(log.getFilter()); log.setFilter(f); assertSame(f, log.getFilter()); }
public void testSetFilter_AnonyLoggerSufficientPrivilege() { Logger log = Logger.getAnonymousLogger(); Filter f = new MockFilter(); assertNull(log.getFilter()); log.setFilter(f); assertSame(f, log.getFilter()); }
/** * {@inheritDoc} */ @Override public void onEnable () { super.onEnable (); // Okay let me get this straight: This is not nice in any way imaginable but that stupid manager annoys // the hell out of me ... { Filter originalFilter = this.getProxy ().getLogger ().getFilter (); this.getProxy ().getLogger ().setFilter (new UltimateSecurityManagerFilter ()); try { this.grid = new Grid (this); } finally { this.getProxy ().getLogger ().setFilter (originalFilter); } } this.getProxy ().registerChannel (PluginChannelListener.CHANNEL_NAME); // Event Listeners { this.getProxy ().getPluginManager ().registerListener (this, new PluginChannelListener (this)); this.getProxy ().getPluginManager ().registerListener (this, new PlayerListener (this)); } // Commands { this.getProxy ().getPluginManager ().registerCommand (this, new ChannelCommand (this)); this.getProxy ().getPluginManager ().registerCommand (this, new GlobalChannelCommand (this)); this.getProxy ().getPluginManager ().registerCommand (this, new ServerChannelCommand (this)); this.getProxy ().getPluginManager ().registerCommand (this, new SubscribeChannelCommand (this)); this.getProxy ().getPluginManager ().registerCommand (this, new UnsubscribeChannelCommand (this)); } }
@Override public boolean isLoggable(LogRecord record) { if(record==null){ return false; } int levelValue = getLevel().intValue(); if (record.getLevel().intValue() < levelValue || levelValue == offValue) { return false; } Filter filter = getFilter(); if (filter == null) { return true; } return filter.isLoggable(record); }
/** * 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; } }; }
@Override public boolean isLoggable(LogRecord record) { for (Filter filter : filters) { if (!filter.isLoggable(record)) { return false; } } return true; }
@Override public Filter inject() { if (isInjected()) { return logger.getFilter(); } previousFilter = logger.getFilter(); logger.setFilter(this); if (QuietCordPlugin.DEBUG_MODE) { logger.log(Level.INFO, "[QuietCord] This logger is now filtered by {0}", this); } return logger.getFilter(); }
@Test public void testInject__alone() throws Exception { Logger logger = Logger.getLogger("testing"); new PropagatingFilterA(logger).inject(); Filter injected = logger.getFilter(); assertThat("filter wrongly matched arbitrary message alone", injected.isLoggable(rec(ARBITRARY_TEXT)), is(true)); assertThat("filter A didn't match ignored message alone", injected.isLoggable(rec(IGNORED_BY_A)), is(false)); }
/** * Configures logging to write all output to the console. */ private static void configureLoggingConsole() { Logger rootLogger = Logger.getLogger(""); // Remove any existing handlers. for (Handler handler : rootLogger.getHandlers()) { rootLogger.removeHandler(handler); } // add a debug-file // try { // Handler fileHandler = new FileHandler("e:\\libosm.osmbin.debug.log"); // fileHandler.setLevel(Level.FINEST); // fileHandler.setFormatter(new SimpleFormatter()); // Logger.getLogger("org.openstreetmap.osm.data.osmbin").addHandler(fileHandler); // } catch (Exception e) { // System.err.println("Could not create debug-log for tracing osmbin"); // e.printStackTrace(); // } // Add a new console handler. Handler consoleHandler = new StdoutConsoleHandler(); consoleHandler.setLevel(Level.FINER); consoleHandler.setFilter(new Filter() { @Override public boolean isLoggable(final LogRecord aRecord) { Level level = aRecord.getLevel(); return !level.equals(Level.WARNING) && !level.equals(Level.SEVERE); } }); rootLogger.addHandler(consoleHandler); Handler consoleHandlerErr = new ConsoleHandler(); consoleHandlerErr.setLevel(Level.WARNING); rootLogger.addHandler(consoleHandlerErr); }
/** * Sets the logging level for the filter. * * @param level The logging level that shall be used. */ private void setFilterLevel(final Level level) { JavaLogger javaLogger = new JavaLogger(); javaLogger.setFilter(new Filter() { public boolean isLoggable(LogRecord logRecord) { if (logRecord.getLevel().intValue() >= level.intValue()) { logRecords.add(logRecord); } return false; } }); EASyLoggerFactory.INSTANCE.setLogger(javaLogger); }