Logging Hierarchies


When you retrieve a logger using the Logger class method getLogger, the Logger code returns either a new Logger object or an existing Logger object if the Logger has already created one with the same name. Calling Logger.getLogger (Student.class.getName()) creates a logger with the name "sis.studentinfo.Student". Using this fully qualified class name for a Logger is usually sufficient.

The following language tests shows how getLogger returns the same Logger object when called twice with the same name:

 public void testLoggingHierarchy() {    Logger logger = Logger.getLogger("sis.studentinfo.Student");    assertTrue(logger == Logger.getLogger("sis.studentinfo.Student")); } 

The fully qualified name of a class represents a hierarchical relationship. The top level of the hierarchy, or tree, is sis. The next lower level is studentinfo. Each class within studentinfo is a leaf on the tree. You can see this hierarchy more clearly by looking at the directory structure in which Java creates compiled class files.

You can take advantage of this naming hierarchy with respect to logging. The logging facility creates an analogous hierarchy of Logger objects. If you create a logger named sis.studentinfo.Student, its parent is sis.studentinfo. The parent of a logger named sis.studentinfo is named sis. You can demonstrate this by adding to the language test:

 public void testLoggingHierarchy() {    Logger logger = Logger.getLogger("sis.studentinfo.Student");    assertTrue(logger == Logger.getLogger("sis.studentinfo.Student"));    Logger parent = Logger.getLogger("sis.studentinfo");    assertEquals(parent, logger.getParent());    assertEquals(Logger.getLogger("sis"), parent.getParent()); } 

The benefit of this hierarchy is that you can set logging levels at a higher level. For example, you can set the logging level to Level.ALL at the sis logger. A child logger uses the logging level of its parent if it has none itself.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net