Java Reference
In-Depth Information
run.log4jdemo:
[java] 1 [main] INFO com.darwinsys - I created an object: java.lang.
Object@bb6086
BUILD SUCCESSFUL
Total time: 1 second
A more typical use of logging might be to catch an
Exception
and log it, as shown in
Example 16-12. Log4j—catching and logging
public
public class
class
Log4JDemo2
Log4JDemo2
{
public
public static
static
void
void
main
(
String
[]
args
) {
Logger theLogger
=
Logger
.
getLogger
(
"com.darwinsys"
);
try
try
{
Object o
=
new
new
Object
();
theLogger
.
info
(
"I created an object: "
+
o
);
iif
(
o
!=
null
null
) {
// bogus, just to show logging
throw
throw new
new
IllegalArgumentException
(
"Just testing"
);
}
}
catch
catch
(
Exception ex
) {
theLogger
.
error
(
"Caught Exception: "
+
ex
,
ex
);
}
}
}
Much of the flexibility of the
log4j
package stems from its use of external configuration
files; you can enable or disable logging without recompiling the application. A properties file
that eliminates all logging might have this entry:
log4j.rootLogger=FATAL, APP1
Only fatal error messages print; all levels less than that are ignored.
To log from a client to a server on a remote machine, the
org.apache.log4j.net
package
includes several
Appender
s and servers to connect them to.