Java Reference
In-Depth Information
Solution
Get a
Logger
and use its
log()
method or the convenience methods. Control logging by
changing a properties file. Use the
org.apache.log4j.net
package to make it network
based.
Discussion
Logging using
log4j
is simple, convenient, and flexible. You need to get a
Logger
object
from the static method
Logger.getLogger()
, pass in a configuration identifier that can
either be a hierarchical name (e.g.,
com.darwinsys
) or a
Class
object (e.g.,
MyApp.class
)
that generates the full package and class name. This name can be used in the configuration
file to specify the level of detail that you want to see from the logger. The
Logger
has public
void methods (
debug()
,
info()
,
warn()
,
error()
, and
fatal()
), each of which takes one
Object
to be logged (and an optional
Throwable
). As with
System.out.println()
, if you
pass in anything that is not a
String
, its
toString()
method is called. A generic logging
method is also included:
public void log(Level level, Object message);
The
Level
class is defined in the
log4j
package. The standard levels are in this order:
DEBUG
<
INFO
<
WARN
<
ERROR
<
FATAL
. So debug messages are least important, and fatal are most
important. Each
Logger
has a level associated with it; messages whose level is less than the
Logger
's level are silently discarded.
A simple application can log messages using these few statements:
public
public class
class
Log4JDemo
Log4JDemo
{
public
public static
static
void
void
main
(
String
[]
args
) {
Logger myLogger
=
Logger
.
getLogger
(
"com.darwinsys"
);
// PropertyConfigurator.configure("log4j.properties");
Object o
=
new
new
Object
();
myLogger
.
info
(
"I created an object: "
+
o
);
}
}