Bug 40611 - Bad subclass example; NullPointerException in Loggers created outside Hierarchy
Summary: Bad subclass example; NullPointerException in Loggers created outside Hierarchy
Status: NEW
Alias: None
Product: Log4j - Now in Jira
Classification: Unclassified
Component: Other (show other bugs)
Version: 1.2
Hardware: All All
: P2 trivial
Target Milestone: ---
Assignee: log4j-dev
Depends on:
Reported: 2006-09-27 05:23 UTC by Michael Armida
Modified: 2006-09-26 22:45 UTC (History)
0 users


Note You need to log in before you can comment on or make changes to this bug.
Description Michael Armida 2006-09-27 05:23:05 UTC
The example code in example/subclass shows instantiation of custom logger
subclasses like this: 

MyLogger c = (MyLogger) MyLogger.getLogger("some.cat");

It does not mention that this mechanism relies on the external configuration
file providing necessary attributes to the new logger.  Thus, programmatically
created subclass instances need to do extra work to make sure that the logger
works properly.

To properly create a logger registered with the current Hierarchy, the example
should show something like:

MyLoggerFactory factory = new MyLoggerFactory();
MyLogger c = (MyLogger) LogManager.getLogger("some.logger", factory);

...with the distinction that "some.logger" could be a dynamically-generated
logger name that does not need to be referenced in an external configuration file.

Further, if one does not do this, and then tries to add an Appender to the
Logger, you get a NullPointerException (Category.java:162); this is because the
Logger isn't part of the LoggerRepository, and has a null value for this.repository.

A note should be added to Logger.getParent() that describes why there's no
setParent() and how you go about getting a Logger with a parent.

It should also be documented that LoggerFactory implementations cannot use
makeNewLoggerInstance() to initialize the state of the returned logger in ways
that may seem otherwise normal to a factory - e.g. you can't add Appenders to
the logger in that function.  This is because the function must return before
the logger is added to the Hierarchy before things like Appenders can be added
without the above exception.

Finally, it seems that a lot of the instances of getLogger() are misleading;
since they're meant only to be used by Log4j internals.  Again, it seems to me
that only the various forms of LogManager.getLogger() should be usable by
outside callers; the other versions of getLogger() could do with some renaming
or commenting to discourage mistaken explorations similar to mine.
Comment 1 Michael Armida 2006-09-27 05:45:30 UTC
If you agree these changes should be made, I'm happy to spend time putting
together suggested patches for some or all of the above.  I just want to make
sure it's useful first.