public void testReadConfigurationInputStream_root() throws IOException { InputStream stream = EnvironmentHelper.PropertiesToInputStream(props); manager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props)); Logger logger = new MockLogger("testReadConfigurationInputStream_root.foo", null); Logger root = manager.getLogger(""); Logger logger2 = Logger.getLogger("testReadConfigurationInputStream_root.foo2"); manager.addLogger(logger); assertNull(logger.getLevel()); assertEquals(0, logger.getHandlers().length); assertSame(root, logger.getParent()); assertNull(logger2.getLevel()); assertEquals(0, logger2.getHandlers().length); assertSame(root, logger2.getParent()); // if (!hasConfigClass) { assertEquals(Level.FINE, root.getLevel()); assertEquals(2, root.getHandlers().length); // } // after read stream manager.readConfiguration(stream); assertEquals(Level.FINE, root.getLevel()); assertEquals(2, root.getHandlers().length); assertNull(logger.getLevel()); assertEquals(0, logger.getHandlers().length); stream.close(); }
public void testAddSimiliarLogger() { Logger root = new MockLogger("testAddSimiliarLogger", null); Logger foo = new MockLogger("testAddSimiliarLogger.foo", null); Logger similiarFoo = new MockLogger("testAddSimiliarLogger.fop", null); Logger fooo = new MockLogger("testAddSimiliarLogger.fooo", null); Logger fooChild = new MockLogger("testAddSimiliarLogger.foo.child", null); Logger similiarFooChild = new MockLogger("testAddSimiliarLogger.fop.child", null); Logger foooChild = new MockLogger("testAddSimiliarLogger.fooo.child", null); manager.addLogger(root); manager.addLogger(fooChild); manager.addLogger(similiarFooChild); manager.addLogger(foooChild); assertSame(root, fooChild.getParent()); assertSame(root, similiarFooChild.getParent()); assertSame(root, foooChild.getParent()); manager.addLogger(foo); assertSame(foo, fooChild.getParent()); assertSame(root, similiarFooChild.getParent()); assertSame(root, foooChild.getParent()); manager.addLogger(similiarFoo); assertSame(foo, fooChild.getParent()); assertSame(similiarFoo, similiarFooChild.getParent()); assertSame(root, foooChild.getParent()); manager.addLogger(fooo); assertSame(fooo, foooChild.getParent()); }
protected static void setupSidlogger(Level lvl) { if (!Level.OFF.equals(lvl)) { Filter bslf = new BoshSidLoggerFilter(); Logger BoshConnectionManagerLogger = Logger.getLogger(BoshConnectionManager.class.getName()); Logger BoshSessionLogger = Logger.getLogger(BoshSession.class.getName()); if (BoshConnectionManagerLogger.getLevel() == null || BoshSessionLogger.getLevel() == null || BoshConnectionManagerLogger.getLevel().intValue() < lvl.intValue()) { BoshConnectionManagerLogger.setLevel(lvl); BoshConnectionManagerLogger.setFilter(bslf); BoshSessionLogger.setLevel(lvl); BoshSessionLogger.setFilter(bslf); BoshConnectionManagerLogger.getParent().setFilter(bslf); } try { if (null == sidFilehandler) { sidFilehandler = new FileHandler("logs/bosh_sid.log", 10000000, 5, false); sidFilehandler.setLevel(lvl); sidFilehandler.setFilter(bslf); BoshConnectionManagerLogger.getParent().addHandler(sidFilehandler); } } catch (IOException ex) { log.log(Level.CONFIG, "Error creating BOSH SID logger" + ex); } } }
public void testAddGetLogger_addRoot() throws IOException { Logger foo = new MockLogger(FOO, null); Logger fooChild = new MockLogger(FOO + ".child", null); Logger other = new MockLogger("other", null); Logger root = new MockLogger("", null); assertNull(foo.getParent()); assertNull(root.getParent()); assertNull(other.getParent()); // add root to mock logmanager and it works as "root" logger assertTrue(mockManager.addLogger(foo)); assertTrue(mockManager.addLogger(other)); assertTrue(mockManager.addLogger(fooChild)); assertNull(foo.getParent()); assertNull(other.getParent()); assertSame(foo, fooChild.getParent()); assertTrue(mockManager.addLogger(root)); assertSame(root, foo.getParent()); assertSame(root, other.getParent()); assertNull(root.getParent()); // try to add root logger to non-mock LogManager, no effect assertFalse(manager.addLogger(root)); assertNotSame(root, manager.getLogger("")); }
private void copyLogger(Logger logger) { setLevel(logger.getLevel()); setUseParentHandlers(logger.getUseParentHandlers()); if (logger.getFilter() != null) setFilter(logger.getFilter()); if (logger.getParent() != null) setParent(logger.getParent()); Handler handlers[] = logger.getHandlers(); for (int i = 0; i < handlers.length; i++) { addHandler(handlers[i]); } }
public void testAddGetLogger() { Logger log = new MockLogger(FOO, null); Logger foo = mockManager.getLogger(FOO); assertNull(foo); assertTrue(mockManager.addLogger(log)); foo = mockManager.getLogger(FOO); assertSame(foo, log); assertNull(foo.getParent()); try { mockManager.addLogger(null); fail("add null should throw NullPointerException"); } catch (NullPointerException e) { } try { mockManager.getLogger(null); fail("get null should throw NullPointerException"); } catch (NullPointerException e) { } assertNull(mockManager.getLogger("bad name")); Enumeration<String> enumar = mockManager.getLoggerNames(); int i = 0; while (enumar.hasMoreElements()) { String name = (String) enumar.nextElement(); i++; assertEquals(FOO, name); } assertEquals(i, 1); }
/** * Searches the logger parent hierarchy of the provided {@code Logger} until a parent is found * who has {@code Handler} instances, and then adds those handlers to the provided logger. Note * that this method also modifies the logger to not use its parent handlers in order to prevent * duplicate log entries. */ private void attachParentHandlers() { Logger parent = this; do { parent = parent.getParent(); } while (parent != null && parent.getHandlers().length == 0); if (parent == null) { // NOTE: this case should never happen since we would // eventually hit the LogManager$RootLogger which by default // has a Handler. However a developer could feasibly adjust // some settings so that the RootLogger had no handler and none // of the child Loggers did as well. return; } // Add all of the parent handlers to this Logger so that we can // later wrap it. Handler[] arr = parent.getHandlers(); for (Handler h : arr) { addHandler(h); } // Now that we are using the same handler as the parent, avoid // propagating the call to the parent Logger as this will result in // duplicate log entries to the handler. setUseParentHandlers(false); }
static Optional<String> run(String[] args) { int argCount = args.length; if (argCount < 3 || argCount > 4) { return Optional.of(USAGE); } try { Logging.init(); Logger log = Logger.getLogger(DeaggCalc.class.getName()); Path tempLog = HazardCalc.createTempLog(); FileHandler fh = new FileHandler(tempLog.getFileName().toString()); fh.setFormatter(new Logging.ConsoleFormatter()); log.getParent().addHandler(fh); log.info(PROGRAM + ": initializing..."); Path modelPath = Paths.get(args[0]); HazardModel model = HazardModel.load(modelPath); CalcConfig config = model.config(); if (argCount == 4) { Path userConfigPath = Paths.get(args[3]); config = CalcConfig.Builder.copyOf(model.config()) .extend(CalcConfig.Builder.fromFile(userConfigPath)) .build(); } log.info(config.toString()); log.info(""); Sites sites = HazardCalc.readSites(args[1], config, log); log.info("Sites: " + sites); double returnPeriod = Double.valueOf(args[2]); Path out = calc(model, config, sites, returnPeriod, log); // transfer log and write config Files.move(tempLog, out.resolve(PROGRAM + ".log")); config.write(out); log.info(PROGRAM + ": finished"); return Optional.absent(); } catch (Exception e) { StringBuilder sb = new StringBuilder() .append(NEWLINE) .append(PROGRAM + ": error") .append(NEWLINE) .append(" Arguments: ") .append(Arrays.toString(args)) .append(NEWLINE) .append(NEWLINE) .append(Throwables.getStackTraceAsString(e)) .append(USAGE); return Optional.of(sb.toString()); } }
/** * Retrieves a list of root loggers. * * @return list of root loggers. */ private Set<Logger> getRootLoggers() { final LogManager logManager = LogManager.getLogManager(); final Enumeration<String> loggerNames = logManager.getLoggerNames(); final Set<Logger> rootLoggers = Sets.newHashSet(); while (loggerNames.hasMoreElements()) { Logger logger = logManager.getLogger(loggerNames.nextElement()); if (logger != null) { while (logger.getParent() != null) { logger = logger.getParent(); } rootLoggers.add(logger); } } return rootLoggers; }
private static void setVlog(Logger logger, LogLevel logLevel) { final Level newLevel = logLevel.getLevel(); logger.setLevel(newLevel); do { for (Handler handler : logger.getHandlers()) { Level handlerLevel = handler.getLevel(); if (newLevel.intValue() < handlerLevel.intValue()) { handler.setLevel(newLevel); } } } while (logger.getUseParentHandlers() && (logger = logger.getParent()) != null); }
public String getParentLoggerName(String loggerName) { Logger l = logManager.getLogger(loggerName); if (l == null) { return null; } Logger p = l.getParent(); if (p == null) { // root logger return EMPTY_STRING; } else { return p.getName(); } }
public void testDefaultLoggerProperties() throws Exception { // mock LogManager has no default logger assertNull(mockManager.getLogger("")); assertNull(mockManager.getLogger("global")); // non-mock LogManager has two default logger Logger global = manager.getLogger("global"); Logger root = manager.getLogger(""); assertSame(global, Logger.global); assertSame(root, global.getParent()); // root properties manager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props)); assertNull(root.getFilter()); assertEquals(2, root.getHandlers().length); assertEquals(Level.FINE, root.getLevel()); assertEquals("", root.getName()); assertSame(root.getParent(), null); assertNull(root.getResourceBundle()); assertNull(root.getResourceBundleName()); assertTrue(root.getUseParentHandlers()); }
/* * (non-Javadoc) * * @see java.util.logging.LoggingMXBean#getParentLoggerName(java.lang.String) */ public String getParentLoggerName(String loggerName) { String result = null; Logger logger = LogManager.getLogManager().getLogger(loggerName); if (logger != null) { // The named Logger exists. Now attempt to obtain its parent. Logger parent = logger.getParent(); if (parent != null) { // There is a parent result = parent.getName(); } else { // logger must be the root Logger result = ""; } } return result; }
public void testValidConfigClass() throws Exception { String oldPropertyValue = System.getProperty(CONFIG_CLASS); try { System.setProperty(CONFIG_CLASS, this.getClass().getName() + "$ConfigClass"); assertNull(manager.getLogger("testConfigClass.foo")); manager.readConfiguration(); assertNull(manager.getLogger("testConfigClass.foo")); Logger l = Logger.getLogger("testConfigClass.foo.child"); assertSame(Level.FINEST, manager.getLogger("").getLevel()); assertEquals(0, manager.getLogger("").getHandlers().length); assertEquals("testConfigClass.foo", l.getParent().getName()); } finally { Properties systemProperties = System.getProperties(); if (oldPropertyValue != null) { systemProperties.setProperty(CONFIG_CLASS, oldPropertyValue); } else { systemProperties.remove(CONFIG_CLASS); } } }
public Level setLevel(final String iLevel, final Class<? extends Handler> iHandler) { final Level level = iLevel != null ? Level.parse(iLevel.toUpperCase(Locale.ENGLISH)) : Level.INFO; if (level.intValue() < minimumLevel.intValue()) { // UPDATE MINIMUM LEVEL minimumLevel = level; if (level.equals(Level.FINER) || level.equals(Level.FINE) || level.equals(Level.FINEST)) debug = info = warn = error = true; else if (level.equals(Level.INFO)) { info = warn = error = true; debug = false; } else if (level.equals(Level.WARNING)) { warn = error = true; debug = info = false; } else if (level.equals(Level.SEVERE)) { error = true; debug = info = warn = false; } } Logger log = Logger.getLogger(DEFAULT_LOG); while (log != null) { log.setLevel(level); for (Handler h : log.getHandlers()) { if (h.getClass().isAssignableFrom(iHandler)) { h.setLevel(level); break; } } log = log.getParent(); } return level; }
private void addToFamilyTree(Logger logger, String name) { Logger parent = null; // find parent int lastSeparator; String parentName = name; while ((lastSeparator = parentName.lastIndexOf('.')) != -1) { parentName = parentName.substring(0, lastSeparator); parent = loggers.get(parentName); if (parent != null) { setParent(logger, parent); break; } else if (getProperty(parentName + ".level") != null || getProperty(parentName + ".handlers") != null) { parent = Logger.getLogger(parentName); setParent(logger, parent); break; } } if (parent == null && (parent = loggers.get("")) != null) { setParent(logger, parent); } // find children // TODO: performance can be improved here? String nameDot = name + '.'; Collection<Logger> allLoggers = loggers.values(); for (final Logger child : allLoggers) { Logger oldParent = child.getParent(); if (parent == oldParent && (name.length() == 0 || child.getName().startsWith(nameDot))) { final Logger thisLogger = logger; child.setParent(thisLogger); if (oldParent != null) { // -- remove from old parent as the parent has been changed oldParent.children.remove(child); } } } }
@Before public void setUp() throws Exception { serverNode = new SgsTestNode("TestNodeMappingServiceImpl", null, null); txnProxy = serverNode.getProxy(); logger = Logger.getLogger("testLogger"); // Find a parent with handlers, which we'll wrap with a transactional // handler. This mimics the actions of the TransactionalLogManager. Logger parent = logger; while (parent != null) { parent = parent.getParent(); if (parent.getHandlers().length != 0) { break; } } assert (parent != null); for (Handler h : parent.getHandlers()) { Handler newHandler = ctor.newInstance(txnProxy, h); logger.addHandler(newHandler); parent.removeHandler(h); } logger.setLevel(Level.FINEST); }
/** * Passes a record to registered handlers, provided the record is considered as loggable both by * {@link #isLoggable(Level)} and a possibly installed custom {@link #setFilter(Filter) filter}. * * <p>If the logger has been configured to use parent handlers, the record will be forwarded to * the parent of this logger in addition to being processed by the handlers registered with this * logger. * * <p>The other logging methods in this class are convenience methods that merely create a new * LogRecord and pass it to this method. Therefore, subclasses usually just need to override this * single method for customizing the logging behavior. * * @param record the log record to be inspected and possibly forwarded. */ public void log(LogRecord record) { synchronized (lock) { if (!isLoggable(record.getLevel())) return; if ((filter != null) && !filter.isLoggable(record)) return; /* * If no logger name has been set for the log record, use the name of * this logger. */ if (record.getLoggerName() == null) record.setLoggerName(name); /* * Avoid that some other thread is changing the logger hierarchy while * we are traversing it. */ synchronized (LogManager.getLogManager()) { Logger curLogger = this; do { /* * The Sun J2SE 1.4 reference implementation seems to call the * filter only for the logger whose log method is called, never * for any of its parents. Also, parent loggers publish log * record whatever their level might be. This is pretty weird, * but GNU Classpath tries to be as compatible as possible to * the reference implementation. */ for (int i = 0; i < curLogger.handlers.length; i++) curLogger.handlers[i].publish(record); if (curLogger.getUseParentHandlers() == false) break; curLogger = curLogger.getParent(); } while (parent != null); } } }
public void testAddGetLogger_Hierachy() { Logger foo = new MockLogger("testAddGetLogger_Hierachy.foo", null); Logger child = new MockLogger("testAddGetLogger_Hierachy.foo.child", null); Logger fakeChild = new MockLogger("testAddGetLogger_Hierachy.foo2.child", null); Logger grandson = new MockLogger("testAddGetLogger_Hierachy.foo.child.grandson", null); Logger otherChild = new MockLogger("testAddGetLogger_Hierachy.foo.child", null); assertNull(foo.getParent()); assertNull(child.getParent()); assertNull(grandson.getParent()); assertNull(otherChild.getParent()); // whenever a logger is added to a LogManager, hierarchy will be updated // accordingly assertTrue(mockManager.addLogger(child)); assertNull(child.getParent()); assertTrue(mockManager.addLogger(fakeChild)); assertNull(fakeChild.getParent()); assertTrue(mockManager.addLogger(grandson)); assertSame(child, grandson.getParent()); assertTrue(mockManager.addLogger(foo)); assertSame(foo, child.getParent()); assertNull(foo.getParent()); assertNull(fakeChild.getParent()); // but for non-mock LogManager, foo's parent should be root assertTrue(manager.addLogger(foo)); assertSame( manager.getLogger(""), manager.getLogger("testAddGetLogger_Hierachy.foo").getParent()); // if we add one logger to two LogManager, parent will changed assertTrue(manager.addLogger(otherChild)); assertTrue(manager.addLogger(grandson)); assertSame(foo, otherChild.getParent()); assertSame(otherChild, grandson.getParent()); }
/** @see java.util.logging.Logger#getParent() */ @Override public Logger getParent() { return delegate.getParent(); }
/** * Adds a named logger. If a logger with the same name has * already been registered, the method returns <code>false</code> * without adding the logger. * * <p>The <code>LogManager</code> only keeps weak references * to registered loggers. Therefore, names can become available * after automatic garbage collection. * * @param logger the logger to be added. * * @return <code>true<code>if <code>logger</code> was added, * <code>false</code> otherwise. * * @throws NullPointerException if <code>name<code> is * <code>null</code>. */ public synchronized boolean addLogger(Logger logger) { /* To developers thinking about to remove the 'synchronized' * declaration from this method: Please read the comment * in java.util.logging.Logger.getLogger(String, String) * and make sure that whatever you change wrt. synchronization * does not endanger thread-safety of Logger.getLogger. * The current implementation of Logger.getLogger assumes * that LogManager does its synchronization on the globally * shared instance of LogManager. */ String name; WeakReference ref; /* This will throw a NullPointerException if logger is null, * as required by the API specification. */ name = logger.getName(); ref = (WeakReference) loggers.get(name); if (ref != null) { if (ref.get() != null) return false; /* There has been a logger under this name in the past, * but it has been garbage collected. */ loggers.remove(ref); } /* Adding a named logger requires a security permission. */ if ((name != null) && !name.equals("")) checkAccess(); Logger parent = findAncestor(logger); loggers.put(name, new WeakReference(logger)); if (parent != logger.getParent()) logger.setParent(parent); /* It can happen that existing loggers should be children of * the newly added logger. For example, assume that there * already exist loggers under the names "", "foo", and "foo.bar.baz". * When adding "foo.bar", the logger "foo.bar.baz" should change * its parent to "foo.bar". */ if (parent != rootLogger) { for (Iterator iter = loggers.keySet().iterator(); iter.hasNext();) { Logger possChild = (Logger) ((WeakReference) loggers.get(iter.next())).get(); if ((possChild == null) || (possChild == logger) || (possChild.getParent() != parent)) continue; if (!possChild.getName().startsWith(name)) continue; if (possChild.getName().charAt(name.length()) != '.') continue; possChild.setParent(logger); } } return true; }
protected Logger getBaseLogger() { return logger.getParent(); }
public void testAddLoggerReverseOrder() { Logger root = new MockLogger("testAddLoggerReverseOrder", null); Logger foo = new MockLogger("testAddLoggerReverseOrder.foo", null); Logger fooChild = new MockLogger("testAddLoggerReverseOrder.foo.child", null); Logger fooGrandChild = new MockLogger("testAddLoggerReverseOrder.foo.child.grand", null); Logger fooGrandChild2 = new MockLogger("testAddLoggerReverseOrder.foo.child.grand2", null); Logger realRoot = manager.getLogger(""); manager.addLogger(fooGrandChild); assertEquals(realRoot, fooGrandChild.getParent()); manager.addLogger(root); assertSame(root, fooGrandChild.getParent()); assertSame(realRoot, root.getParent()); manager.addLogger(foo); assertSame(root, foo.getParent()); assertSame(foo, fooGrandChild.getParent()); manager.addLogger(fooGrandChild2); assertSame(foo, fooGrandChild2.getParent()); assertSame(foo, fooGrandChild.getParent()); manager.addLogger(fooChild); assertSame(fooChild, fooGrandChild2.getParent()); assertSame(fooChild, fooGrandChild.getParent()); assertSame(foo, fooChild.getParent()); assertSame(root, foo.getParent()); assertSame(realRoot, root.getParent()); }