Java Reference
In-Depth Information
If you compile and run this program with no
log4j.properties
file, it complains and does not
produce any logging output:
ant run.log4jdemo
Buildfile: build.xml
run.log4jdemo:
[java] log4j:WARN No appenders could be found for logger (com.darwinsys).
[java] log4j:WARN Please initialize the log4j system properly.
So we need to create a configuration file, whose default name is
log4j.properties
. You can
also provide the logfile name via System Properties:
-Dlog4j.configuration=URL
.
Every
Logger
has a
Level
to specify what level of messages to write, and an
Appender
,
which is the code that writes the messages out. A
ConsoleAppender
writes to
System.out
,
of course; other loggers write to files, operating system-level loggers, and so on. A simple
configuration file looks something like this:
# Set root logger level to DEBUG and its only appender to APP1.
log4j.rootLogger=DEBUG, APP1
# APP1 is set to be a ConsoleAppender.
log4j.appender.APP1=org.apache.log4j.ConsoleAppender
# APP1 uses PatternLayout.
log4j.appender.APP1.layout=org.apache.log4j.PatternLayout
log4j.appender.APP1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
This file gives the root logger a level of DEBUG—write all messages—and an appender of
APP1, which is configured on the next few lines. Note that I didn't have to refer to the
com.darwinsys Logger
; because every
Logger
inherits from the root logger, a simple ap-
plication needs to configure only the root logger. The properties file can also be an XML
document or you can write your own configuration parser (almost nobody does this). With
the preceding file in place, the demonstration works better:
$
ant run.log4jdemo
Buildfile: build.xml
init:
build: