Java Reference
In-Depth Information
As with
log4j
, every
Logger
object has a given logging level, and messages below that
level are silently discarded:
public
public
void
void
setLevel
(
java
.
util
.
logging
.
Level
);
public
public
java
.
util
.
logging
.
Level
getLevel
( );
public
public
boolean
boolean
isLoggable
(
java
.
util
.
logging
.
Level
);
As with
log4j
, objects handle the writing of the log. Each logger has a
Handler
:
public
public synchronized
synchronized
void
void
addHandler
(
java
.
util
.
logging
.
Handler
);
public
public synchronized
synchronized
void
void
removeHandler
(
java
.
util
.
logging
.
Handler
);
public
public synchronized
synchronized
java
.
util
.
logging
.
Handler
[]
getHandlers
( );
and each
Handler
has a
Formatter
, which formats a
LogRecord
for display. By providing
your own
Formatter
, you have more control over how the information being passed into the
log gets formatted.
Unlike
log4j
, the Java SE logging mechanism has a default configuration, so
Example 16-13
is a minimal logging example program.
Example 16-13. Log14Demo.java
public
public class
class
Log14Demo
Log14Demo
{
public
public static
static
void
void
main
(
String
[]
args
) {
Logger myLogger
=
Logger
.
getLogger
(
"com.darwinsys"
);
Object o
=
new
new
Object
();
myLogger
.
info
(
"I created an object: "
+
o
);
}
}
Running it prints the following:
C:>
java logging.Log14Demo
Mar 8, 2014 7:48:26 PM Log14Demo main
INFO: I created an object: java.lang.Object@57f0dc
C:>
As with
log4j
, the typical use is in logging caught exceptions; the code for this is in