Java Logging APIs
Java Logging APIs
Abstract
This is the Public Review draft of the Java Logging APIs proposed in JSR-047.
There are change bars relative to the Community Review draft (0.50).
1 Requirements
This section outlines the main requirements and goals for the Java Logging APIs.
1.3.3 Filters
In addition to having logging levels, it is also desirable to support a more general filter mech-
anism so that application code can attach arbitrary filters to control logging output.
1.5 Internationalization
The Logging Framework should support easy internationalization of log messages.
The support for internationalization should be based on the normal internationalization support
in the Java platform.
Logger Handler
application outside world
The LogManager class keeps track of a set of global Handlers. By default all Loggers send their
output to this standard set of global Handlers. But Loggers may also be configured to ignore
the global Handler list and/or to send output to specific target Handlers.
Some Handlers may direct output to other Handlers. For example, the MemoryHandler main-
tains an internal ring buffer of LogRecords and on trigger events it publishes its LogRecords
through a target Handler. In such cases, any formatting is done by the last Handler in the chain.
The APIs are structured so that calls on the Logger APIs can be cheap when logging is disabled.
If logging is disabled for a given log level, then the Logger can make a cheap comparison test
and return. If logging is enabled for a given log level, the Logger is still careful to minimize
costs before passing the LogRecord into the Handlers. In particular, localization and formatting
(which are relatively expensive) are deferred until the Handler requests them. For example, a
MemoryHandler can maintain a circular buffer of LogRecords without having to pay format-
ting costs.
2.3 Loggers
Client code sends log request to Logger objects. Each logger keeps track of a log level that it
is interested in and discards log requests that are below this level.
Loggers are normally named entities, using dot separated names such as “java.awt”. The
namespace is hierarchical and is managed by the LogManager. The namespace should typically
be aligned with the Java packaging namespace, but is not required to follow it slavishly. For
example, a Logger called “java.awt” might handle logging requests for classes in the java.awt
package, but it might also handle logging for classes in sun.awt that support the client-visible
abstractions defined in the java.awt package.
In addition to named Loggers, it is also possible to create anonymous Loggers that don’t appear
in the shared namespace. See Section 2.14.
By default, loggers send their output to a set of global Handlers managed by the LogManager
infrastructure class (see 2.7 below).
The LogManager class allows log levels to be updated for named loggers. Setting a level for a
given named Logger will also affect all its children. So setting a log level for “javax.swing”
will also affect javax.swing.text” and “javax.swing.table” and “javax.swing.table.header”. The
LogManager keeps track of level settings and when a new named Logger is created it is as-
signed the appropriate Level for its point in the naming hierarchy.
First, there are methods that take an explicit source class name and source method name. These
methods are intended for developers who want to be able to quickly locate the source of any
given logging message. An example of this style is:
void warning(String sourceClass, String sourceMethod, String msg);
Second, there are a set of methods that do not take explicit source class or source method
names. These are intended for developers who want easy-to-use logging and do not require de-
tailed source information.
void warning(String msg);
For this second set of methods, the Logging framework will make a “best effort” to determine
which class and method called into the logging framework and will add this information into
the LogRecord. However, it is important to realize that this automatically inferred information
may only be approximate. The latest generation of virtual machines do extensive optimizations
when JITing and may entirely remove stack frames, making it impossible to reliably locate the
calling class and method.
Note to reviewers: This is exactly the same situation as with Throwable backtraces. The information in
a Throwable backtrace is also only approximate. This issue has been discussed with the Java Virtual Ma-
chine spec lead, and it is clear that the current JVM spec does not require that accurate call stack infor-
mation be provided and it is also very unlikely that such a requirement would be added, as it would
prevent potential JIT optimizations.
2.5 Handlers
The following handlers will be provided as part of J2SE:
• StreamHandler. A simple handler for writing formatted records to an OutputStream.
• ConsoleHandler. A simple handler for writing formatted records to System.err.
• FileHandler. A handler to write formatted log records to either a single file, or a set of
rotating log files.
• SocketHandler. A handler to write formatted log records to remote TCP ports.
• MemoryHandler. A handler to buffer log records in memory.
It is fairly straightforward to develop new Handlers. Developers requiring specific functional-
ity can either develop a Handler from scratch, or subclass one of the provided Handlers.
2.6 Formatters
J2SE will include two standard Formatters:
• XMLFormatter. Writes detailed XML structured information.
• SimpleFormatter. Write brief “human readable” summaries of log records.
As with Handlers it is fairly straightforward to develop new Formatters.
• A hierarchical namespace of named Loggers. This includes recording the logging level
settings for various points in the namespace, which can be used to initialize the logging
levels for new Loggers.
• A set of logging control properties read from the configuration file (see 2.8 below).
• A set of “global Handlers” that are the default handlers used by all Loggers (unless they
are disabled for a given Logger)
There is a single LogManager object that can be retrieved using the static LogManager.getLog-
Manager object. This is created during LogManager initialization, based on a system property.
This property allows container applications (such as EJB containers) to substitute their own
subclass of LogManager in place of the default class.
2.14 Security
The principal security requirement is that untrusted code should not be able to change the log-
ging configuration. Specifically, if the logging configuration has been set up to log a particular
category of information to a particular handler, then untrusted code should not be able to pre-
vent or disrupt that logging.
A new security permission LoggingPermission is defined to control updates to the logging con-
figuration.
Trusted applications are given the appropriate LoggingPermission so they can call any of the
logging configuration APIs. Untrusted applets are a different story. Untrusted applets can cre-
ate and use named Loggers in the normal way, but they are not allowed to change logging con-
trol settings, such as adding or removing handlers, or changing logging levels. However
untrusted applets are able to create and use their own “anonymous” Loggers, using Logger.get-
AnonymousLogger. These anonymous Loggers are not registered in the global namespace and
their methods are not access checked, allowing even untrusted code to change their logging
control settings.
The logging framework does not attempt to prevent spoofing. The sources of logging calls can-
not be determined reliably, so when a LogRecord is published that claims to be from a partic-
ular source class and source method, it may be a fabrication. Similarly, formatters such as the
XMLFormatter do not attempt to protect themselves against nested log messages inside mes-
sage strings. Thus, a spoof LogRecord might contain a spoof set of XML inside its message
string to make it look as if there was an additional XML record in the output.
In addition, the logging framework does not attempt to protect itself against denial of service
attacks. Any given logging client can flood the logging framework with meaningless messages
in an attempt to conceal some important log message.
2.16 Packaging
All the Logging classes are in the java.* part of the namespace, in the java.util.logging package.
This helps to emphasize that they are part of the core platform and that people can rely on them
being available.
2.17 Localization
Log messages may need to be localized.
Each Logger may have a Resource Bundle name associated with it. The corresponding Re-
source Bundle can be used to map between raw message strings and localized message strings.
Normally localization will be performed by Formatters. As a convenience, the Formatter class
provides a formatMessage method that provides some basic localization and formatting sup-
port.
Typically, J2EE containers will provide standard output Handlers for use by J2EE components.
So typically J2EE components (such as EJBs) should not expect to create their own Handler
classes, but should expect to use standard Handlers that have been configured as part of the
container. However, J2EE components can freely create their own named Logger objects that
use the standard Handlers.
3 Examples
3.1 Simple use
Here’s a small program that does logging using the default configuration.
This program relies on the global handlers that were established by the LogManager based on
the configuration file. It creates its own Logger object and then makes calls to that Logger ob-
ject to report various events.
package com.wombat;
import java.util.logging.*;
public class Nose {
// Obtain a suitable logger.
private static Logger logger = Logger.getLogger(“com.wombat.nose”);
public static void main(String argv[]) {
// Log a FINE tracing message
logger.fine(“doing stuff”);
try {
Wombat.sneeze();
} catch (Error ex) {
// Log the Error.
logger.log(Level.WARNING, “trouble sneezing”, ex);
}
logger.fine(“done”);
}
}
package
java.util.logging
Class Summary
Interfaces
Filter A Filter can be used to provide fine grain control over what is logged, beyond the con-
trol provided by log levels.
Classes
ConsoleHandler This handler publishes log records to System.err.
FileHandler Simple file logging Handler.
Formatter A Formatter provides support for formatting LogRecords.
Handler A Handler object takes log messages from a Logger and exports them.
Level The Level class defines a set of standard logging levels that can be used to control log-
ging output.
Logger A Logger object is used to log messages for a specific system or application compo-
nent.
LoggingPermission The permission which the SecurityManager will check when code that is running with
a SecurityManager calls one of the logging control methods (such as LogManager.set-
Level).
LogManager There is a single global LogManager object that is used to maintain a set of shared
state about Loggers and log services.
LogRecord LogRecord objects are used to pass logging requests between the logging framework
and individual log Handlers.
MemoryHandler Handler that buffers requests in a circular buffer in memory.
SimpleFormatter Print a brief summary of the LogRecord in a human readable format.
SocketHandler Simple network logging handler.
StreamHandler Stream based logging Handler.
XMLFormatter Format a LogRecord into a standard XML format.
java.util.logging
ConsoleHandler
Syntax
public class ConsoleHandler extends java.util.logging.StreamHandler
java.lang.Object
|
+--java.util.logging.Handler
|
+--java.util.logging.StreamHandler
|
+--java.util.logging.ConsoleHandler
Description
This handler publishes log records to System.err. By default the SimpleFormatter is used to generate brief summaries.
Configuration: By default each ConsoleHandler is initialized using the following LogManager configuration properties.
If properties are not defined (or have invalid values) then the specified default values are used.
• java.util.logging.ConsoleHandler.level specifies the default level for the Handler (defaults to Level.INFO).
• java.util.logging.ConsoleHandler.filter specifies the name of a Filter class to use (defaults to no Filter).
• java.util.logging.ConsoleHandler.formatter specifies the name of a Formatter class to use (defaults to java.util.log-
ging.SimpleFormatter).
• java.util.logging.ConsoleHandler.encoding the name of the character set encoding to use (defaults to the default
platform encoding).
Since: 1.4
Member Summary
Constructors
ConsoleHandler() Create a ConsoleHandler for System.err.
Methods
close() Override "StreamHandler.close" to do a flush but not to close the output stream.
publish(LogRecord) Publish a LogRecord.
Constructors
ConsoleHandler()
public ConsoleHandler()
Methods
close()
public void close()
Override "StreamHandler.close" to do a flush but not to close the output stream. That is, we do not close System.err.
Overrides: StreamHandler.close() in class StreamHandler
publish(LogRecord)
public void publish(LogRecord record)
Publish a LogRecord.
The logging request was made initially to a Logger object, which initialized the LogRecord and forwarded it here.
Overrides: StreamHandler.publish(LogRecord) in class StreamHandler
Parameters:
record - description of the log event
java.util.logging
FileHandler
Syntax
public class FileHandler extends java.util.logging.StreamHandler
java.lang.Object
|
+--java.util.logging.Handler
|
+--java.util.logging.StreamHandler
|
+--java.util.logging.FileHandler
Description
Simple file logging Handler.
The Handler can either write to a specified file, or it can write to a rotating set of files.
For a rotating set of files, as each file reaches a given size limit, it is closed, rotated out, and a new file opened. Succes-
sively older files are named by adding "0", "1", "2", etc into the base filename.
By default buffering is enabled in the IO libraries but each log record is flushed out when it is complete.
By default the XMLFormatter class is used for formatting.
Configuration: By default each FileHandler is initialized using the following LogManager configuration properties. If
properties are not defined (or have invalid values) then the specified default values are used.
• java.util.logging.FileHandler.level specifies the default level for the Handler (defaults to Level.ALL).
• java.util.logging.FileHandler.filter specifies the name of a Filter class to use (defaults to no Filter).
• java.util.logging.FileHandler.formatter specifies the name of a Formatter class to use (defaults to java.util.log-
ging.XMLFormatter)
• java.util.logging.FileHandler.encoding the name of the character set encoding to use (defaults to the default platform
encoding).
• java.util.logging.FileHandler.limit specifies an approximate maximum amount to write (in bytes) to any one file. If
this is zero, then there is no limit. (Defaults to no limit).
• java.util.logging.FileHandler.count specifies how many output files to cycle through (defaults to 1).
• java.util.logging.FileHandler.pattern specifies a pattern for generating the output file name. See below for details.
(Defaults to "%t/java.log").
A pattern consists of a string that includes the following special components that will be replaced at runtime:
• "/" the local pathname separator
• "%t" the system temporary directory
• "%h" the value of the "user.home" system property
• "%g" the generation number to distinguish rotated logs
• "%u" a unique number to resolve conflicts
• "%%" translates to a single percent sign "%"
If no "%g" field has been specified and the file count is greater than one, then the generation number will be added to the
end of the generated filename, after a dot.
Thus for example a pattern of "%t/java%g.log" with a count of 2 would typically cause log files to be written on Solaris
to /var/tmp/java0.log and /var/tmp/java1.log whereas on Windows 95 they would be typically written to to
C:\TEMP\java0.log and C:\TEMP\java1.log
Generation numbers follow the sequence 0, 1, 2, etc.
Normally the "%u" unique field is set to 0. However, if the FileHandler tries to open the filename and finds the file is cur-
rently in use by another process it will increment the unique number field and try again. This will be repeated until File-
Handler finds a file name that is not currently in use. If there is a conflict and no "%u" field has been specified, it will be
added at the end of the filename after a dot. (This will be after any automatically added generation number.)
Thus if three processes were all trying to log to fred%u.%g.txt then they might end up using fred0.0.txt, fred1.0.txt,
fred2.0.txt as the first file in their rotating sequences.
Note that the use of unique ids to avoid conflicts is only guaranteed to work reliably when using a local disk file system.
Since: 1.4
Member Summary
Constructors
FileHandler() Construct a default FileHandler.
FileHandler(String) Initialize a FileHandler to write to the given filename.
FileHandler(String, Initialize a FileHandler to write to a set of files.
int, int)
Methods
close() Close all the files.
publish(LogRecord) Format and publish a LogRecord.
Constructors
FileHandler()
public FileHandler()
Construct a default FileHandler. This will be configured entirely from LogManager properties (or their default val-
ues).
Throws: SecurityException - if a security manager exists and if the caller does not have
LoggingPermission("control").
FileHandler(String)
public FileHandler(java.lang.String pattern)
Parameters:
pattern - the name of the output file
Throws: SecurityException - if a security manager exists and if the caller does not have
LoggingPermission("control").
Initialize a FileHandler to write to a set of files. When (approximately) the given limit has been written to one file,
another file will be opened. The output will cycle through a set of count files.
The FileHandler is configured based on LogManager properties (or their default values) except that the given pattern
argument is used as the filename pattern, the file limit is set to the limit argument, and the file count is set to the
given count argument.
The count must be at least 1.
Parameters:
pattern - the pattern for naming the output file
limit - the maximum number of bytes to write to any one file
count - the number of files to use
Throws: SecurityException - if a security manager exists and if the caller does not have
LoggingPermission("control").
Methods
close()
public void close()
publish(LogRecord)
public void publish(LogRecord record)
java.util.logging
Filter
Syntax
public interface Filter
Description
A Filter can be used to provide fine grain control over what is logged, beyond the control provided by log levels.
Each Logger and each Handler can have a filter associated with it. The Logger or Handler will call the isLoggable
method to check if a given LogRecord should be published. If isLoggable returns false, the LogRecord will be discarded.
Since: 1.4
Member Summary
Methods
isLoggable(LogRecord) Check if a given log record should be published.
Methods
isLoggable(LogRecord)
public boolean isLoggable(LogRecord record)
java.util.logging
Formatter
Syntax
public abstract class Formatter
java.lang.Object
|
+--java.util.logging.Formatter
Description
A Formatter provides support for formatting LogRecords.
Typically each logging Handler will have a Formatter associated with it. The Formatter takes a LogRecord and converts
it to a string.
Some formatters (such as the XMLFormatter) need to wrap head and tail strings around a set of formatted records. The
getHeader and getTail methods can be used to obtain these strings.
Since: 1.4
Member Summary
Constructors
Formatter() Construct a new formatter.
Methods
format(LogRecord) Format the given log record and return the formatted string.
formatMes- Localize and format the message string from a log record.
sage(LogRecord)
getHead(Handler) Return the header string for a set of formatted records.
getTail(Handler) Return the tail string for a set of formatted records.
Constructors
Formatter()
protected Formatter()
Methods
format(LogRecord)
public abstract java.lang.String format(LogRecord record)
Format the given log record and return the formatted string.
The resulting formatted String will normally include a localized and formated version of the LogRecord's message
field. The LogRecord.formatMessage convenience method can (optionally) be used to localize and format the mes-
sage field.
Parameters:
record - the log record to be formatted.
Returns: the formatted log record
formatMessage(LogRecord)
public java.lang.String formatMessage(LogRecord record)
Localize and format the message string from a log record. This method is provided as a convenience for Formatter
subclasses to use when they are performing formatting.
The message string is first localized to a format string using the record's ResourceBundle. (If there is no Resource-
Bundle, or if the message key is not found, then the key is used as the format string.) The format String may use
either java.text style formatting or (starting in JDK 1.4) printf style formatting:
• If there are no parameters, no formatter is used.
• Otherwise, if the string contains "{0" then java.text.MessageFormat is used to format the string.
• Otherwise printf style formatting is used.
NOTE TO REVIEWERS: I am making a forward reference here to the printf style formatting that is planned for
Merlin. This formatting will be fully internationalizable and is likely to be significantly easier to use than the current
java.text formatting, so it seems useful to support it.
Parameters:
record - the log record containing the raw message
Returns: a localized and formatted message
getHead(Handler)
public java.lang.String getHead(Handler h)
getTail(Handler)
public java.lang.String getTail(Handler h)
This base class returns an empty string, but this may be overriden by subclasses.
Parameters:
h - The target handler.
Returns: tail string
java.util.logging
Handler
Syntax
public abstract class Handler
java.lang.Object
|
+--java.util.logging.Handler
Description
A Handler object takes log messages from a Logger and exports them. It might for example, write them to a console or
write them to a file, or send them to a network logging service, or forward them to an OS log, or whatever.
A Handler can be disabled by doing a setLevel(Level.OFF) and can be re-enabled by doing a setLevel with an appropri-
ate level.
Handler classes typically use LogManager properties to set default values for Filter, Formatter, and Level. See the spe-
cific documentation for each concrete Handler class.
Since: 1.4
Member Summary
Constructors
Handler() Default constructor.
Handler(Formatter) Construct a Handler with the given formatter.
Methods
close() Close the Handler and free all associated resources.
flush() Flush any buffered output.
getEncoding() Return the character encoding for this Handler.
getException() Report on the most recent exception (if any) to have been detected while writing to
this Handler.
getFilter() Get the current filter for this Handler.
getFormatter() Return the Formatter for this Handler.
getLevel() Get the log level specifying which messages will be logged by this Handler.
isLoggable(LogRecord) Check if this Handler would actually log a given LogRecord.
publish(LogRecord) Publish a LogRecord.
setEncoding(String) Set the character encoding used by this Handler.
setException(Excep- Set the most recent IO exception.
tion)
setFilter(Filter) Set a filter to control output on this Handler.
setFormatter(Format- Set a Formatter.
ter)
setLevel(Level) Set the log level specifying which message levels will be logged by this handler.
Constructors
Handler()
protected Handler()
Default constructor. The resulting Handler has a log level of ALL, no formatter, and no filter.
Handler(Formatter)
protected Handler(Formatter formatter)
Methods
close()
public abstract void close()
flush()
public abstract void flush()
getEncoding()
public java.lang.String getEncoding()
getException()
public java.lang.Exception getException()
Report on the most recent exception (if any) to have been detected while writing to this Handler.
Does a "flush" and then reports the underlying IO status. If the most recent write has been successful then the result
will be null. Otherwise it will be an exception value that a subclass has set using setException.
Returns: null if recent IO operations have succeeded, otherwise the most recently detected exception.
getFilter()
public Filter getFilter()
getFormatter()
public Formatter getFormatter()
getLevel()
public Level getLevel()
Get the log level specifying which messages will be logged by this Handler. Message levels lower than this level will
be discarded.
Returns: the level of messages being logged.
isLoggable(LogRecord)
public boolean isLoggable(LogRecord record)
publish(LogRecord)
public abstract void publish(LogRecord record)
Publish a LogRecord.
The logging request was made initially to a Logger object, which initialized the LogRecord and forwarded it here.
The Handler is responsible for formatting the message, when and if necessary. The formatting should include local-
ization.
Parameters:
record - description of the log event
setEncoding(String)
public void setEncoding(java.lang.String encoding)
encoding - The name of a supported character encoding. May be null, to indicate the default platform
encoding.
Throws: SecurityException - if a security manager exists and if the caller does not have
LoggingPermission("control").
UnsupportedEncodingException - if the named encoding is not supported.
setException(Exception)
protected void setException(java.lang.Exception exception)
setFilter(Filter)
public void setFilter(Filter newFilter)
setFormatter(Formatter)
public void setFormatter(Formatter newFormatter)
Set a Formatter. This formatter will be used to format LogRecords for this Handler.
Some Handlers may not use Formatters, in which case the formatter will be remembered, but not used.
Parameters:
newFormatter - the formatter to use (may not be null)
Throws: SecurityException - if a security manager exists and if the caller does not have
LoggingPermission("control").
setLevel(Level)
public void setLevel(Level newLevel)
Set the log level specifying which message levels will be logged by this handler. Message levels lower than this
value will be discarded.
The intention is to allow developers to turn on voluminous logging, but to limit the messages that are sent to certain
Handlers.
Parameters:
newLevel - the new value for the log level
Throws: SecurityException - if a security manager exists and if the caller does not have
LoggingPermission("control").
java.util.logging
Level
Syntax
public class Level implements java.io.Serializable
java.lang.Object
|
+--java.util.logging.Level
Description
The Level class defines a set of standard logging levels that can be used to control logging output. The logging Level
objects are ordered and are specified by ordered integers. Enabling logging at a given level also enables logging at all
higher levels.
Clients should normally use the predefined Level constants such as Level.SEVERE.
The levels in descending order are:
• SEVERE (highest value)
• WARNING
• INFO
• CONFIG
• FINE
• FINER
• FINEST (lowest value)
In addition there is a level OFF that can be used to turn off logging, and a level ALL that can be used to enable logging
of all messages.
It is possible for third parties to define additional logging levels by subclassing Level. In such cases subclasses should
take care to chose unique integer level values and to ensure that they maintain the Object uniqueness property across
serialization by defining a suitable readResolve method.
Since: 1.4
Member Summary
Fields
ALL ALL indicates that all messages should be logged.
CONFIG CONFIG is a message level for static configuration messages.
FINE FINE is a message level providing tracing information.
FINER FINER indicates a fairly detailed tracing message.
FINEST FINEST indicates a highly detailed tracing message
INFO INFO is a message level for informational messages.
OFF OFF is a special level that can be used to turn off logging.
SEVERE SEVERE is a message level indicating a serious failure.
Member Summary
WARNING WARNING is a message level indicating a potential problem.
Constructors
Level(String, int) Create a named Level with a given integer value.
Methods
equals(Object) Compare two objects for value equality.
hashCode() Generate a hashcode.
intValue() Get the integer value for this level.
parse(String) Parse a level name string into a Level.
toString()
Fields
ALL
public static final Level ALL
CONFIG
public static final Level CONFIG
FINE
public static final Level FINE
FINER
public static final Level FINER
FINER indicates a fairly detailed tracing message. By default logging calls for entering, returning, or throwing an
exception are traced at this level.
FINEST
public static final Level FINEST
INFO
public static final Level INFO
OFF
public static final Level OFF
SEVERE
public static final Level SEVERE
WARNING
public static final Level WARNING
Constructors
Level(String, int)
protected Level(java.lang.String name, int value)
Methods
equals(Object)
public boolean equals(java.lang.Object ox)
hashCode()
public int hashCode()
Generate a hashcode.
Overrides: java.lang.Object.hashCode() in class java.lang.Object
Returns: a hashcode based on the level value
intValue()
public final int intValue()
Get the integer value for this level. This integer value can be used for efficient ordering comparisons between Level
objects.
Returns: the integer value for this level.
parse(String)
public static Level parse(java.lang.String name)
toString()
public final java.lang.String toString()
java.util.logging
Logger
Syntax
public class Logger
java.lang.Object
|
+--java.util.logging.Logger
Description
A Logger object is used to log messages for a specific system or application component. Loggers are normally named,
using a hierarchical dot-separated namespace. Logger names can be arbitrary strings, but they should normally be based
on the package name or class name of the logged component, such as java.net or javax.swing. In additon it is possible to
create "anonymous" Loggers that are not stored in the Logger namespace.
Logger objects may be obtained by calls on one of the getLogger factory methods. These will either create a new Logger
or return a suitable existing Logger.
Logging messages will be forwarded to registered Handler objects, which can forward the messages to a variety of des-
tinations, including consoles, files, OS logs, etc.
On each logging call the Logger initially performs a cheap check of the request level (e.g. SEVERE or FINE) against a
log level maintained by the logger. If the request level is lower than the log level, the logging call returns immediately.
The log level is originally initialized based on the properties from the logging configuration file, as described in the
description of the LogManager class. However it may also be dynamically changed by calls on the Logger.setLevel or
LogManager.setLevel methods.
After passing this initial (cheap) test, the Logger will allocate a LogRecord to describe the logging message. It will then
call a Filter (if present) to do a more detailed check on whether the record should be published. If that passes it will then
publish the LogRecord to the target Handlers.
Most of the logger output methods take a "msg" argument. This msg argument may be either a raw value or a localiza-
tion key. During formatting, if the logger has a localization ResourceBundle and if the ResourceBundle has a mapping
for the msg string, then the msg string is replaced by the localized value. Otherwise the original msg string is used.
Formatting (including localization) is the responsibility of the output Handler, which will typically call a Formatter.
Note that formatting need not occur synchronously. It may be delayed until a LogRecord is actually written to an exter-
nal sink.
There are various logging convenience methods:
First, to make it easier to identify the source of a logging request there are a set of logging methods that take the source
class name and the source method name. For example:
• void warning(String sourceClass, string sourceMethod, String msg);
Second, for developers who do not wish to provide this source information there are also methods that do not require
these arguments. For example:
• void warning(String msg);
For this second set of methods, the Logging framework will make a "best effort" to determine which class and method
called into the logging method. However, it is important to realize that this automatically inferred information may only
be approximate (or may even be quite wrong!). Virtual machines are allowed to do extensive optimizations when JITing
and may entirely remove stack frames, making it impossible to reliably locate the calling class and method.
All methods on Logger are multi-thread safe.
Subclassing Information: Subclasses of Logger are required to provide their own getLogger factory methods. In
order to intercept all logging output, subclasses need only override the log(LogRecord) method. All the other
log() methods are implemented as calls on this log(LogRecord) method.
Since: 1.4
Member Summary
Fields
global The "global" Logger object is provided as a convenience to developers who are mak-
ing casual use of the Logging package.
Constructors
Logger(String, Protected method to construct a logger for a named subsystem.
String)
Methods
addHandler(Handler) Add a log Handler to receive logging messages.
config(String) Log a CONFIG message.
config(String, Log a CONFIG message, with an array of object arguments.
Object[])
config(String, Log a CONFIG message, specifying source class and method.
String, String)
config(String, Log a CONFIG message, specifying source class and method, with an array of object
String, String, arguments.
Object[])
entering(String, Log a procedure entry.
String)
entering(String, Log a procedure entry, with parameters.
String, Object[])
exiting(String, Log a procedure return.
String)
exiting(String, Log a procedure return, with result object.
String, Object)
fine(String) Log a FINE message.
fine(String, Log a FINE message, with an array of object arguments.
Object[])
fine(String, String, Log a FINE message, specifying source class and method.
String)
fine(String, String, Log a FINE message, specifying source class and method, with an array of object
String, Object[]) arguments.
finer(String) Log a FINER message.
finer(String, Log a FINER message, with an array of object arguments.
Object[])
finer(String, String, Log a FINER message, specifying source class and method.
String)
finer(String, String, Log a FINER message, specifying source class and method, with an array of object
String, Object[]) arguments.
finest(String) Log a FINEST message.
finest(String, Log a FINEST message, with an array of object arguments.
Object[])
Member Summary
finest(String, Log a FINEST message, specifying source class and method.
String, String)
finest(String, Log a FINEST message, specifying source class and method, with an array of object
String, String, arguments.
Object[])
getAnonymousLogger() Create an anonymous Logger.
getAnonymousLog- Create an anonymous Logger.
ger(String)
getFilter() Get the current filter for this Logger.
getHandlers() Get the Handlers associated with this logger.
getLevel() Get the log level specifying which messages will be logged by this logger.
getLogger(String) Find or create a logger for a named subsystem.
getLogger(String, Find or create a logger for a named subsystem.
String)
getName() Get the name for this logger.
getResourceBundle() Retrieve the localization resource bundle for this logger.
getResourceBundle- Retrieve the localization resource bundle name for this logger.
Name()
getUseGlobalHan- Discover whether or not this logger is sending its output to the set of global handlers
dlers() managed by the LogManager.
info(String) Log an INFO message.
info(String, Log an INFO message, with an array of object arguments.
Object[])
info(String, String, Log an INFO message, specifying source class and method.
String)
info(String, String, Log an INFO message, specifying source class and method, with an array of object
String, Object[]) arguments.
isLoggable(Level) Check if a message of the given level would actually be logged by this logger.
log(Level, String) Log a message, with no arguments.
log(Level, String, Log a message, with an array of object arguments.
Object[])
log(Level, String, Log a message, specifying source class and method, with no arguments.
String, String)
log(Level, String, Log a message, specifying source class and method, with an array of object argu-
String, String, ments.
Object[])
log(Level, String, Log a message, specifying source class and method, with associated Throwable infor-
String, String, Throw- mation.
able)
log(Level, String, Log a message, with associated Throwable information.
Throwable)
log(LogRecord) Log a LogRecord.
removeHandler(Han- Remove a log Handler.
dler)
setFilter(Filter) Set a filter to control output on this Logger.
setLevel(Level) Set the log level specifying which message levels will be logged by this logger.
setUseGlobalHan- Specify whether or not this logger should send its output to the set of global handlers
dlers(boolean) managed by the LogManager.
severe(String) Log a SEVERE message.
severe(String, Log a SEVERE message, with an array of object arguments.
Object[])
severe(String, Log a SEVERE message, specifying source class and method.
String, String)
severe(String, Log a SEVERE message, specifying source class and method, with an array of object
String, String, arguments.
Object[])
Member Summary
throwing(String, Log throwing an exception.
String, Throwable)
warning(String) Log a WARNING message.
warning(String, Log a WARNING message, with an array of object arguments.
Object[])
warning(String, Log a WARNING message, specifying source class and method.
String, String)
warning(String, Log a WARNING message, specifying source class and method, with an array of
String, String, object arguments.
Object[])
Fields
global
public static final Logger global
The "global" Logger object is provided as a convenience to developers who are making casual use of the Logging
package. Developers who are making serious use of the logging package (for example in products) should create
and use their own Logger objects, with appropriate names, so that logging can be controlled on a suitable per-Log-
ger granularity.
The global logger is initialized by calling Logger.getLogger("global").
Constructors
Logger(String, String)
protected Logger(java.lang.String name, java.lang.String resourceBundleName)
Methods
addHandler(Handler)
public void addHandler(Handler handler)
config(String)
public void config(java.lang.String msg)
config(String, Object[])
public void config(java.lang.String msg, java.lang.Object[] params)
Log a CONFIG message, specifying source class and method, with an array of object arguments.
If the logger is currently enabled for the CONFIG message level then the given message is forwarded to all the reg-
istered output Handler objects.
Parameters:
sourceClass - name of class that issued the logging request
sourceMethod - name of method that issued the logging request
msg - The string message (or a key in the message catalog)
params - array of parameters to the message
entering(String, String)
public void entering(java.lang.String sourceClass, java.lang.String sourceMethod)
exiting(String, String)
public void exiting(java.lang.String sourceClass, java.lang.String sourceMethod)
fine(String)
public void fine(java.lang.String msg)
fine(String, Object[])
public void fine(java.lang.String msg, java.lang.Object[] params)
Log a FINE message, specifying source class and method, with an array of object arguments.
If the logger is currently enabled for the FINE message level then the given message is forwarded to all the regis-
tered output Handler objects.
Parameters:
sourceClass - name of class that issued the logging request
sourceMethod - name of method that issued the logging request
msg - The string message (or a key in the message catalog)
params - array of parameters to the message
finer(String)
public void finer(java.lang.String msg)
finer(String, Object[])
public void finer(java.lang.String msg, java.lang.Object[] params)
Log a FINER message, specifying source class and method, with an array of object arguments.
If the logger is currently enabled for the FINER message level then the given message is forwarded to all the regis-
tered output Handler objects.
Parameters:
sourceClass - name of class that issued the logging request
sourceMethod - name of method that issued the logging request
msg - The string message (or a key in the message catalog)
params - array of parameters to the message
finest(String)
public void finest(java.lang.String msg)
finest(String, Object[])
public void finest(java.lang.String msg, java.lang.Object[] params)
Log a FINEST message, specifying source class and method, with an array of object arguments.
If the logger is currently enabled for the FINEST message level then the given message is forwarded to all the regis-
tered output Handler objects.
Parameters:
sourceClass - name of class that issued the logging request
sourceMethod - name of method that issued the logging request
msg - The string message (or a key in the message catalog)
params - array of parameters to the message
getAnonymousLogger()
public static Logger getAnonymousLogger()
Create an anonymous Logger. The newly created Logger is not registered in the LogManager namespace and will
not be affected by updates to the logging configuration or by calls on LogManager.setLevel. There will also be no
access checks on updates to the logger.
This factory method is primarily intended for use from applets. Because the resulting Logger is anonymous it can be
kept private by the creating class. This removes the need for normal security checks, which in turn allows untrusted
applet code to update the control state of the Logger. For example an applet can do a setLevel or an addHandler on
an anonymous Logger.
The new logger is initially configured with the logging level for the root name ("") from the LogManager class. It is
initially configured to use the LogManager's global handlers.
Returns: a newly created private Logger
getAnonymousLogger(String)
public static Logger getAnonymousLogger(java.lang.String resourceBundleName)
Create an anonymous Logger. The newly created Logger is not registered in the LogManager namespace and will
not be affected by updates to the logging configuration or by calls on LogManager.setLevel. There will also be no
access checks on updates to the Logger.
This factory method is primarily intended for use from applets. Because the resulting Logger is anonymous it can be
kept private by the creating class. This removes the need for normal security checks, which in turn allows untrusted
applet code to update the control state of the Logger. For example an applet can do a setLevel or an addHandler on
an anonymous Logger.
The new logger is initially configured with the logging level for the root name ("") from the LogManager class. It is
initially configured to use the LogManager's global handlers.
Parameters:
resourceBundleName - name of ResourceBundle to be used for localizing messages for this logger.
Returns: a newly created private Logger
Throws: MissingResourceException - if the named ResourceBundle cannot be found.
getFilter()
getHandlers()
public Handler[] getHandlers()
getLevel()
public Level getLevel()
Get the log level specifying which messages will be logged by this logger. Message levels lower than this level will
be discarded.
Returns: the level of messages being logged.
getLogger(String)
public static Logger getLogger(java.lang.String name)
Find or create a logger for a named subsystem. If a logger has already been created with the given name it is
returned. Otherwise a new logger is created.
If a new logger is created its log level will be configured based on the LogManager configuration and it will config-
ured to send logging output to all global output Handlers. It will be registered in the LogManager global namespace.
This will mean it will be affected by subsequent LogManager.setLevel calls.
Parameters:
name - A name for the logger. This should be a dot-separated name and should normally be based on the
package name or class name of the subsystem, such as java.net or javax.swing
Returns: a suitable Logger
getLogger(String, String)
public static Logger getLogger(java.lang.String name, java.lang.String resourceBundleName)
Find or create a logger for a named subsystem. If a logger has already been created with the given name it is
returned. Otherwise a new logger is created.
If a new logger is created its log level will be configured based on the LogManager and it will configured to send
logging output to all global output Handlers. It will be registered in the LogManager global namespace. This will
mean it will be affected by subsequent LogManager.setLevel calls.
If the named Logger already exists and does not yet have a localization resource bundle then the given resource bun-
dle name is used. If the named Logger already exists and has a different resource bundle name then an IllegalArgu-
mentException is thrown.
Parameters:
name - A name for the logger. This should be a dot-separated name and should normally be based on the
package name or class name of the subsystem, such as java.net or javax.swing
resourceBundleName - name of ResourceBundle to be used for localizing messages for this logger.
Returns: a suitable Logger
Throws: MissingResourceException - if the named ResourceBundle cannot be found.
IllegalArgumentName - if the Logger already exists and uses a different resource bundle name.
getName()
public java.lang.String getName()
getResourceBundle()
public java.util.ResourceBundle getResourceBundle()
getResourceBundleName()
public java.lang.String getResourceBundleName()
getUseGlobalHandlers()
public boolean getUseGlobalHandlers()
Discover whether or not this logger is sending its output to the set of global handlers managed by the LogManager.
Returns: true if output is to be sent to the LogManager's global handlers.
info(String)
public void info(java.lang.String msg)
info(String, Object[])
public void info(java.lang.String msg, java.lang.Object[] params)
If the logger is currently enabled for the INFO message level then the given message is forwarded to all the regis-
tered output Handler objects.
Parameters:
msg - The string message (or a key in the message catalog)
params - array of parameters to the message
Log an INFO message, specifying source class and method, with an array of object arguments.
If the logger is currently enabled for the INFO message level then the given message is forwarded to all the regis-
tered output Handler objects.
Parameters:
sourceClass - name of class that issued the logging request
sourceMethod - name of method that issued the logging request
msg - The string message (or a key in the message catalog)
params - array of parameters to the message
isLoggable(Level)
public boolean isLoggable(Level level)
Check if a message of the given level would actually be logged by this logger.
Parameters:
level - a message logging level
Returns: true if the given message level is currently being logged.
log(Level, String)
public void log(Level level, java.lang.String msg)
If the logger is currently enabled for the given message level then the given message is forwarded to all the regis-
tered output Handler objects.
Parameters:
level - One of the message level identifiers, e.g. SEVERE
msg - The string message (or a key in the message catalog)
Log a message, specifying source class and method, with an array of object arguments.
If the logger is currently enabled for the given message level then a corresponding LogRecord is created and for-
warded to all the registered output Handler objects.
Parameters:
level - One of the message level identifiers, e.g. SEVERE
sourceClass - name of class that issued the logging request
sourceMethod - name of method that issued the logging request
msg - The string message (or a key in the message catalog)
params - array of parameters to the message
Log a message, specifying source class and method, with associated Throwable information.
If the logger is currently enabled for the given message level then the given arguments are stored in a LogRecord
which is forwarded to all registered output handlers.
Note that the thrown argument is stored in the LogRecord thrown property, rather than the LogRecord parameters
property. Thus is it processed specially by output Formatters and is not treated as a formatting parameter to the
LogRecord message property.
Parameters:
level - One of the message level identifiers, e.g. SEVERE
sourceClass - name of class that issued the logging request
sourceMethod - name of method that issued the logging request
msg - The string message (or a key in the message catalog)
thrown - Throwable associated with log message.
log(LogRecord)
public void log(LogRecord record)
Log a LogRecord.
All the other logging methods in this class call through this method to actually perform any logging. Subclasses can
override this single method to capture all log activity.
The current logger's name, resource bundle, and resource bundle name will be set into the LogRecord.
Parameters:
record - the LogRecord to be published
removeHandler(Handler)
public void removeHandler(Handler handler)
setFilter(Filter)
public void setFilter(Filter newFilter)
setLevel(Level)
public void setLevel(Level newLevel)
Set the log level specifying which message levels will be logged by this logger. Message levels lower than this value
will be discarded. The level value Level.OFF can be used to turn off logging.
Parameters:
newLevel - the new value for the log level
Throws: SecurityException - if a security manager exists and if the caller does not have
LoggingPermission("control").
setUseGlobalHandlers(boolean)
public void setUseGlobalHandlers(boolean useGlobalHandlers)
Specify whether or not this logger should send its output to the set of global handlers managed by the LogManager.
Parameters:
useGlobalhandlers - true if output is to be sent to the LogManager's global handlers.
Throws: SecurityException - if a security manager exists and if the caller does not have
LoggingPermission("control").
severe(String)
public void severe(java.lang.String msg)
severe(String, Object[])
public void severe(java.lang.String msg, java.lang.Object[] params)
Log a SEVERE message, specifying source class and method, with an array of object arguments.
If the logger is currently enabled for the SEVERE message level then the given message is forwarded to all the reg-
istered output Handler objects.
Parameters:
sourceClass - name of class that issued the logging request
sourceMethod - name of method that issued the logging request
msg - The string message (or a key in the message catalog)
params - array of parameters to the message
Note that the thrown argument is stored in the LogRecord thrown property, rather than the LogRecord parameters
property. Thus is it processed specially by output Formatters and is not treated as a formatting parameter to the
LogRecord message property.
Parameters:
sourceClass - name of class that issued the logging request
sourceMethod - name of the method.
thrown - The Throwable that is being thrown.
warning(String)
public void warning(java.lang.String msg)
warning(String, Object[])
public void warning(java.lang.String msg, java.lang.Object[] params)
Log a WARNING message, specifying source class and method, with an array of object arguments.
If the logger is currently enabled for the WARNING message level then the given message is forwarded to all the
registered output Handler objects.
Parameters:
sourceClass - name of class that issued the logging request
sourceMethod - name of method that issued the logging request
msg - The string message (or a key in the message catalog)
params - array of parameters to the message
java.util.logging
LoggingPermission
Syntax
public final class LoggingPermission extends java.security.BasicPermission
java.lang.Object
|
+--java.security.Permission
|
+--java.security.BasicPermission
|
+--java.util.logging.LoggingPermission
Description
The permission which the SecurityManager will check when code that is running with a SecurityManager calls one of
the logging control methods (such as LogManager.setLevel).
Currently there is only one named LoggingPermission. This is "control" and it grants the ability to control the logging
configuration, for example by adding or removing Handlers, by adding or removing Filters, or by changing logging lev-
els.
Programmers do not normally create LoggingPermission objects directly. Instead they are created by the security policy
code based on reading the security policy file.
Since: 1.4
Member Summary
Constructors
LoggingPermis- Creates a new LoggingPermission object.
sion(String, String)
Constructors
LoggingPermission(String, String)
public LoggingPermission(java.lang.String name, java.lang.String actions)
Creates a new LoggingPermission object. This constructor exists for use by the Policy object to instantiate new Per-
mission objects.
Parameters:
name - Permission name. Must be "control".
actions - Must be either null or the empty string.
java.util.logging
LogManager
Syntax
public class LogManager
java.lang.Object
|
+--java.util.logging.LogManager
Description
There is a single global LogManager object that is used to maintain a set of shared state about Loggers and log services.
This LogManager object:
• Manages a hierarchical namespace of Logger objects. All named Loggers are stored in this namespace.
• Manages a set of logging control properties. These are simple key-value pairs that can be used by Handlers and
other logging objects to configure themselves.
• Manages a list of "global" logging handlers. By default Loggers will publish all (relevant) LogRecords to all the glo-
bal handlers.
The global LogManager object can be retrieved using LogManager.getLogManager(). The LogManager object is created
during class initialization and cannot subsequently be changed.
Note to reviewers: The main reason for having a LogManager object rather than simply a class with static methods is to
allow container applications (especially J2EE containers) to replace the standard LogManager class with their own sub-
classes. We do not support on-the-fly replacement of the LogManager object as that would introduce tricky sychnronza-
tion problems in propagating state between the old and the new objects. Making the LogManager object non-replaceable
also allows client code to cache the object.
At startup the LogManager class is located using the java.util.logging.manager system property.
By default, the LogManager reads its initial configuration from a properties file "lib/logging.properties" in the JRE
directory. If you edit that property file you can change the default logging configuration for all uses of that JRE.
In addition, the LogManager uses two optional system properties that allow more control over reading the initial config-
uration:
• "java.util.logging.config.class"
• "java.util.logging.config.file"
These two properties may be set via the Preferences API, or as command line property definitions to the "java" com-
mand, or as system property definitions passed to JNI_CreateJavaVM.
If the "java.util.logging.config.class" property is set, then the property value is treated as a class name. The given class
will be loaded, an object will be instantiated, and that object's constructor is responsible for reading in the initial config-
uration. (That object may use other system properties to control its configuration.)
If "java.util.logging.config.class" property is not set, then the "java.util.logging.config.file" system property can be used
to specify a properties file (in java.util.Properties format). The initial logging configuration will be read from this file.
If neither of these properties is defined then, as described above, the LogManager will read its initial configuration from
a properties file "lib/logging.properties" in the JRE directory.
The properties for loggers and Handlers will have names starting with the dot-separated name for the handler or logger.
Since: 1.4
Member Summary
Constructors
LogManager() Protected constructor.
Methods
addGlobalHandler(Han- Add a global log Handler to receive output from all loggers.
dler)
addLogger(Logger) Add a named logger.
addPropertyChangeLis- Add an event listener to be invoked when the logging properties are re-read.
tener(PropertyChange-
Listener)
checkAccess() Check that the current context is trusted to modify the logging configuration.
flush() Flush all the global handlers.
getGlobalHandlers() Get an array of all the global Handlers.
getLevel(String) Get the log level for a given logger name.
getLogger(String) Method to find a named logger.
getLoggerNames() Get an enumeration of known logger names.
getLogManager() Return the global LogManager object.
getProperty(String) Get the value of a logging property.
publish(LogRecord) Method to post a log record to all global handlers.
readConfiguration() Reinitialize the logging properties and reread the logging configuration.
readConfigura- Reinitialize the logging properties and reread the logging configuration from the
tion(InputStream) given stream, which should be in java.util.Properties format.
removeAllGlobalHan- Remove all global log handlers.
dlers()
removeGlobalHan- Remove a global log handler.
dler(Handler)
removePropertyChange- Remove an event listener for property change events.
Listener(Property-
ChangeListener)
Member Summary
setLevel(String, Set a log level for a given set of loggers.
Level)
Constructors
LogManager()
protected LogManager()
Protected constructor. This is protected so that conatiner applications (such as J2EE containers) can subclass the
object. It is non-public as it is intended that there only be one LogManager object, whose value is retrieved by call-
ing Logmanager.getLogManager.
Methods
addGlobalHandler(Handler)
public void addGlobalHandler(Handler handler)
addLogger(Logger)
public boolean addLogger(Logger l)
Add a named logger. This does nothing and returns false if a logger with the same name is already registered.
The Logger factory methods call this method to register each newly created Logger.
The application must retain its own reference to the Logger object to avoid it being garbage collected. The LogMan-
ager will only retain a weak reference.
Parameters:
l - the new logger.
Returns: true if the argument logger was registered successfully, false if a logger of that name already exists.
Throws: NullPointerException - if the logger name is null.
addPropertyChangeListener(PropertyChangeListener)
public void addPropertyChangeListener(java.beans.PropertyChangeListener l)
Add an event listener to be invoked when the logging properties are re-read.
Parameters:
l - event listener
Throws: SecurityException - if a security manager exists and if the caller does not have
LoggingPermission("control").
checkAccess()
public void checkAccess()
Check that the current context is trusted to modify the logging configuration. This requires LoggingPermis-
sion("control").
If the check fails we throw a SecurityException, otherwise we return normally.
Throws: SecurityException - if a security manager exists and if the caller does not have
LoggingPermission("control").
flush()
public void flush()
getGlobalHandlers()
public Handler[] getGlobalHandlers()
getLevel(String)
public Level getLevel(java.lang.String name)
Get the log level for a given logger name. See the setLevel method for more details.
Parameters:
name - The logger name
Returns: the log level
getLogger(String)
public Logger getLogger(java.lang.String name)
getLoggerNames()
getLogManager()
public static LogManager getLogManager()
getProperty(String)
public java.lang.String getProperty(java.lang.String name)
publish(LogRecord)
public void publish(LogRecord record)
readConfiguration()
public void readConfiguration()
readConfiguration(InputStream)
public void readConfiguration(java.io.InputStream ins)
Reinitialize the logging properties and reread the logging configuration from the given stream, which should be in
java.util.Properties format. A PropertyChangeEvent will be fired after the properties are read.
All existing global Handlers will be closed and a new set of global Handlers will be created based on the new prop-
erties.
Any log level definitions in the new configuration file will be applied using LogManager.setLevel() in the order they
are read.
Parameters:
ins - stream to read properties from
Throws: SecurityException - if a security manager exists and if the caller does not have
LoggingPermission("control").
removeAllGlobalHandlers()
public void removeAllGlobalHandlers()
removeGlobalHandler(Handler)
public void removeGlobalHandler(Handler handler)
removePropertyChangeListener(PropertyChangeListener)
public void removePropertyChangeListener(java.beans.PropertyChangeListener l)
setLevel(String, Level)
public void setLevel(java.lang.String name, Level level)
Set a log level for a given set of loggers. Subsequently the target loggers will only log messages whose types are
greater than or equal to the given level. The level value Level.OFF can be used to turn off logging.
The given log level applies to the named Logger (if it exists), and on any other named Loggers below that name in
the naming hierarchy. The name and level are recorded, and will be applied to any new Loggers that are later created
matching the given name.
Thus, setting a level on "x.y" would affect loggers called "x.y", "x.y.z", "x.y.foo.bah" but would not affect loggers
called "x.yy" or "x.z".
The empty string "" can be used to identify the root.
Parameters:
name - The logger name to update.
level - the new log level, e.g. Level.SEVERE or Level.FINER
Returns: the previous value of the level
Throws: SecurityException - if a security manager exists and if the caller does not have
LoggingPermission("control").
java.util.logging
LogRecord
Syntax
public class LogRecord implements java.io.Serializable
java.lang.Object
|
+--java.util.logging.LogRecord
Description
LogRecord objects are used to pass logging requests between the logging framework and individual log Handlers.
When a LogRecord is passed into the logging framework it logically belongs to the framework and should no longer be
used or updated by the client application.
Serialization notes:
• The LogRecord class is serializable.
• Because objects in the parameters array may not be serialiable, during serialization all objects in the parameters
array are written as the corresponding Strings (using Object.toString).
• The ResourceBundle is not transmitted as part of the serialized form, but the resource bundle name is, and the recip-
ient object's readObject method will atempt to locate a suitable resource bundle.
• The "thrown" property is transmitted as part of the serialized form, but because the Throwable class does not pre-
serve stack frame information across serialization, the stack frame info will be lost from the "thrown" object. How-
ever, during serialization the writeObject method will ensure that a String version of the stack trace is serialized, and
that String will be available through the getThrownStackTrace method.
Since: 1.4
Member Summary
Constructors
LogRecord(Level, Construct a LogRecord with the given level and message values.
String)
Methods
getLevel() Get the logging message level, for example Level.SEVERE.
getLoggerName() Get the source Logger name's
getMessage() Get the "raw" log message, before localization or formatting.
getMillis() Get event time in milliseconds since 1970.
getParameters() Get the parameters to the log message.
getResourceBundle() Get the localization resource bundle
getResourceBundle- Get the localization resource bundle name
Name()
getSequenceNumber() Get the sequence number.
getSourceClassName() Get the name of the class that (allegedly) issued the logging request.
Member Summary
getSourceMethodName() Get the name of the method that (allegedly) issued the logging request.
getThreadID() Get an identifier for the thread where the message originated.
getThrown() Get any throwable associated with the log record.
getThrownBackTrace() Get a backtrace for any thrown associated with the log record.
setLevel(Level) Set the logging message level, for example Level.SEVERE.
setLoggerName(String) Set the source Logger name.
setMessage(String) Set the "raw" log message, before localization or formatting.
setMillis(long) Set event time.
setParame- Set the parameters to the log message.
ters(Object[])
setResourceBun- Set the localization resource bundle.
dle(ResourceBundle)
setResourceBundle- Set the localization resource bundle name.
Name(String)
setSequenceNum- Set the sequence number.
ber(long)
setSourceClass- Set the name of the class that (allegedly) issued the logging request.
Name(String)
setSourceMethod- Set the name of the method that (allegedly) issued the logging request.
Name(String)
setThreadID(int) Set an identifier for the thread where the message originated.
setThrown(Throwable) Set a throwable associateded with the log event.
Constructors
LogRecord(Level, String)
public LogRecord(Level level, java.lang.String msg)
Methods
getLevel()
public Level getLevel()
getLoggerName()
public java.lang.String getLoggerName()
getMessage()
public java.lang.String getMessage()
getMillis()
public long getMillis()
getParameters()
public java.lang.Object[] getParameters()
getResourceBundle()
public java.util.ResourceBundle getResourceBundle()
getResourceBundleName()
public java.lang.String getResourceBundleName()
This is the name for the ResourceBundle that should be used to localize the message string before formatting it. The
result may be null if the message is not localizable.
Parameters:
bundle - localization bundle name (may be null)
getSequenceNumber()
public long getSequenceNumber()
getSourceClassName()
public java.lang.String getSourceClassName()
Get the name of the class that (allegedly) issued the logging request.
Note that this sourceClassName is not verified and may be spoofed. This information may either have been provided
as part of the logging call, or it may have been inferred automatically by the logging framework. In the latter case,
the information may only be approximate and may in fact describe an earlier call on the stack frame.
May be null if no information could be obtained.
Returns: the source class name
getSourceMethodName()
public java.lang.String getSourceMethodName()
Get the name of the method that (allegedly) issued the logging request.
Note that this sourceMethodName is not verified and may be spoofed. This information may either have been pro-
vided as part of the logging call, or it may have been inferred automatically by the logging framework. In the latter
case, the information may only be approximate and may in fact describe an earlier call on the stack frame.
May be null if no information could be obtained.
Returns: the source method name
getThreadID()
public int getThreadID()
getThrown()
public java.lang.Throwable getThrown()
If the event involved an exception, this will be the exception object. Otherwise null.
Returns: a throwable
getThrownBackTrace()
public java.lang.String getThrownBackTrace()
Get a backtrace for any thrown associated with the log record.
If the event involved an exception, this will be the the backtrace from the exception object. Otherwise it will return
null. The exact backtrace format is implementation specific and will vary beween VMs.
Note that this method is preferrable to obtaining a backtrace from the "getThrown()" Throwable, as the backtrace
may have been lost from that object if it was serialized and then deserialized.
setLevel(Level)
public void setLevel(Level level)
setLoggerName(String)
public void setLoggerName(java.lang.String name)
setMessage(String)
public void setMessage(java.lang.String message)
setMillis(long)
public void setMillis(long millis)
setParameters(Object[])
public void setParameters(java.lang.Object[] parameters)
setResourceBundle(ResourceBundle)
public void setResourceBundle(java.util.ResourceBundle bundle)
setResourceBundleName(String)
public void setResourceBundleName(java.lang.String name)
setSequenceNumber(long)
public void setSequenceNumber(long seq)
setSourceClassName(String)
public void setSourceClassName(java.lang.String sourceClassName)
Set the name of the class that (allegedly) issued the logging request.
Parameters:
sourceClassName - the source class name
setSourceMethodName(String)
public void setSourceMethodName(java.lang.String sourceMethodName)
Set the name of the method that (allegedly) issued the logging request.
Parameters:
sourceMethodName - the source method name
setThreadID(int)
public void setThreadID(int threadID)
setThrown(Throwable)
public void setThrown(java.lang.Throwable thrown)
throwable - a throwable
java.util.logging
MemoryHandler
Syntax
public class MemoryHandler extends java.util.logging.Handler
java.lang.Object
|
+--java.util.logging.Handler
|
+--java.util.logging.MemoryHandler
Description
Handler that buffers requests in a circular buffer in memory.
Normally this Handler simply stores incoming LogRecords into its memory buffer and discards earlier records. This
buffering is very cheap and avoids formatting costs. On certain trigger conditions, the MemoryHandler will push out its
current buffer contents to a target Handler, which will typically publish them to the outside world.
There are three main models for triggering a push of the buffer:
• An incoming LogRecord has a type that is greater than a pre-defined level, the "pushLevel".
• An external class calls the "push" method explicitly.
• A subclass overrides the "log" method and scans each incoming LogRecord and calls "push" if a record matches
some desired criteria.
Configuration: By default each MemoryHandler is initialized using the following LogManager configuration properties.
If properties are not defined (or have invalid values) then the specified default values are used.
• java.util.logging.MemoryHandler.level specifies the level for the Handler (defaults to Level.ALL).
• java.util.logging.MemoryHandler.filter specifies the name of a Filter class to use (defaults to no Filter).
• java.util.logging.MemoryHandler.size defines the buffer size (defaults to 1000).
• java.util.logging.MemoryHandler.push defines the pushLevel (defaults to level.SEVERE).
Since: 1.4
Member Summary
Constructors
MemoryHandler() Create a MemoryHandler and configure it based on LogManager configuration prop-
erties.
MemoryHandler(Han- Create a MemoryHandler.
dler, int, Level)
Methods
close() Close the Handler and free all associated resources.
flush() Causes a flush on the target handler.
getPushLevel() Get the pushLevel.
isLoggable(LogRecord) Check if this Handler would actually log a given LogRecord into its internal buffer.
publish(LogRecord) Store a LogRecord in an internal buffer.
push() Push any buffered output to the target Handler.
Member Summary
setPushLevel(Level) Set the pushLevel.
Constructors
MemoryHandler()
public MemoryHandler()
Create a MemoryHandler.
The MemoryHandler is configured based on LogManager properties (or their default values) except that the given
pushLevel argument and buffer size argument are used.
Parameters:
target - the Handler to which to publish output.
size - the number of log records to buffer
pushLevel - message level to push on
Methods
close()
public void close()
Close the Handler and free all associated resources. This will also close the target Handler.
Overrides: Handler.close() in class Handler
Throws: SecurityException - if a security manager exists and if the caller does not have
LoggingPermission("control").
flush()
public void flush()
getPushLevel()
public Level getPushLevel()
isLoggable(LogRecord)
public boolean isLoggable(LogRecord record)
Check if this Handler would actually log a given LogRecord into its internal buffer.
This method checks if the LogRecord has an appropriate level and whether it satisfies any Filter. However it does
not check whether the LogRecord would result in a "push" of the buffer contents.
Overrides: Handler.isLoggable(LogRecord) in class Handler
Parameters:
record - a LogRecord
Returns: true if the log record would be logged.
publish(LogRecord)
public void publish(LogRecord record)
push()
public void push()
setPushLevel(Level)
public void setPushLevel(Level newLevel)
Set the pushLevel. After a log record is copied into our internal buffer, if its level is greater than or equal to the push-
Level, then "push" will be called.
Parameters:
newLevel - the new value of the pushLevel
Throws: SecurityException - if a security manager exists and if the caller does not have
LoggingPermission("control").
java.util.logging
SimpleFormatter
Syntax
public class SimpleFormatter extends java.util.logging.Formatter
java.lang.Object
|
+--java.util.logging.Formatter
|
+--java.util.logging.SimpleFormatter
Description
Print a brief summary of the LogRecord in a human readable format. The summary will typically be 1 or 2 lines.
Since: 1.4
Member Summary
Constructors
SimpleFormatter()
Methods
format(LogRecord) Format the given LogRecord.
Constructors
SimpleFormatter()
public SimpleFormatter()
Methods
format(LogRecord)
public java.lang.String format(LogRecord record)
java.util.logging
SocketHandler
Syntax
public class SocketHandler extends java.util.logging.StreamHandler
java.lang.Object
|
+--java.util.logging.Handler
|
+--java.util.logging.StreamHandler
|
+--java.util.logging.SocketHandler
Description
Simple network logging handler.
LogRecords are published to a network stream connection. By default the XMLFormatter class is used for formatting.
Configuration: By default each SocketHandler is initialized using the following LogManager configuration properties. If
properties are not defined (or have invalid values) then the specified default values are used.
• java.util.logging.SocketHandler.level specifies the default level for the Handler (defaults to Level.ALL).
• java.util.logging.SocketHandler.filter specifies the name of a Filter class to use (defaults to no Filter).
• java.util.logging.SocketHandler.formatter specifies the name of a Formatter class to use (defaults to java.util.log-
ging.XMLFormatter).
• java.util.logging.SocketHandler.encoding the name of the character set encoding to use (defaults to the default plat-
form encoding).
• java.util.logging.SocketHandler.host specifies the target host name to connect to (no default).
• java.util.logging.SocketHandler.port specifies the target TCP port to use (no default).
The output IO stream is buffered, but is flushed after each log record.
Since: 1.4
Member Summary
Constructors
SocketHandler() Create a SocketHandler, using only LogManager properties (or their defaults).
Sock- Construct a SocketHandler using a specified host and port.
etHandler(String,
int)
Methods
close() Close this output stream.
publish(LogRecord) Format and publish a LogRecord.
Constructors
SocketHandler()
public SocketHandler()
SocketHandler(String, int)
public SocketHandler(java.lang.String host, int port)
Construct a SocketHandler using a specified host and port. The SocketHandler is configured based on LogManager
properties (or their default values) except that the given target host and port arguments are used.
Parameters:
hostName - target host.
port - target port.
Methods
close()
public void close()
publish(LogRecord)
public void publish(LogRecord record)
java.util.logging
StreamHandler
Syntax
public class StreamHandler extends java.util.logging.Handler
java.lang.Object
|
+--java.util.logging.Handler
|
+--java.util.logging.StreamHandler
Description
Stream based logging Handler.
This is primarily intended as a base class or support class to be used in implementing other logging Handlers.
LogRecords are published to a given java.io.OutputStream.
Configuration: By default each StreamHandler is initialized using the following LogManager configuration properties. If
properties are not defined (or have invalid values) then the specified default values are used.
• java.util.logging.StreamHandler.level specifies the default level for the Handler (defaults to Level.ALL).
• java.util.logging.StreamHandler.filter specifies the name of a Filter class to use (defaults to no Filter).
• java.util.logging.StreamHandler.formatter specifies the name of a Formatter class to use (defaults to java.util.log-
ging.SimpleFormatter).
• java.util.logging.StreamHandler.encoding the name of the character set encoding to use (defaults to the default plat-
form encoding).
Since: 1.4
Member Summary
Constructors
StreamHandler() Create a StreamHandler, with no current output stream.
StreamHandler(Output- Create a StreamHandler with a given formatter and output stream.
Stream, Formatter)
Methods
close() Close the current output stream.
flush() Flush any buffered messages.
isLoggable(LogRecord) Check if this Handler would actually log a given LogRecord.
publish(LogRecord) Format and publish a log record.
setEncoding(String) Set (or change) the character encoding used by this Handler.
setOutputStream(Out- Change the output stream.
putStream)
Constructors
StreamHandler()
public StreamHandler()
StreamHandler(OutputStream, Formatter)
public StreamHandler(java.io.OutputStream out, Formatter formatter)
Methods
close()
public void close()
flush()
public void flush()
isLoggable(LogRecord)
public boolean isLoggable(LogRecord record)
Parameters:
record - a LogRecord
Returns: true if the log record would be logged.
publish(LogRecord)
public void publish(LogRecord record)
setEncoding(String)
public void setEncoding(java.lang.String encoding)
setOutputStream(OutputStream)
protected void setOutputStream(java.io.OutputStream out)
java.util.logging
XMLFormatter
Syntax
public class XMLFormatter extends java.util.logging.Formatter
java.lang.Object
|
+--java.util.logging.Formatter
|
+--java.util.logging.XMLFormatter
Description
Format a LogRecord into a standard XML format.
The DTD specification is provided as Appendix A to the Java Logging APIs specification.
The XMLFormatter can be used with arbitrary character encodings, but it is recommended that it normally be used with
UTF-8. The character encoding can be set on the output Handler.
Since: 1.4
Member Summary
Constructors
XMLFormatter()
Methods
format(LogRecord) Format the given message to XML.
getHead(Handler) Return the header string for a set of XML formatted records.
getTail(Handler) Return the tail string for a set of XML formatted records.
Constructors
XMLFormatter()
public XMLFormatter()
Methods
format(LogRecord)
public java.lang.String format(LogRecord record)
getHead(Handler)
public java.lang.String getHead(Handler h)
getTail(Handler)
public java.lang.String getTail(Handler h)
4 Change History
4.1 Changes between 0.50 and 0.55:
• The ConsoleHandler, FileHandler, MemoryHandler, SocketHandler, and
StreamHandler classes now use a LogManager “filter” property to locate a default
Filter class to act as a Filter on the Handler.
• The ConsoleHandler, FileHandler, SocketHandler, and StreamHandler classes now use
a LogManager “formatter” property to locate a default Formatter class to act as the
Formatter on the Handler.
• The ConsoleHandler, FileHandler, SocketHandler, and StreamHandler classes now use
a LogManager “encoding” property to determine a default character set encoding for
the Handler.
• The javadoc in the class header for each of the Handler classes has been revised to be
more consistent in describing LogManager properties and to be clearer on what default
values are used if a property is not defined (or is not valid).
• The javadoc in each of the concrete Handler classes (in both the class header and in the
constructors) has been revised to specify that the LogManager properties (or their
defaults) are used as the default configuration for each Handler, unless explicitly
specified otherwise in a constructor.
• Removed the (false) assumption that XMLFormatter should always use UTF-8. I have
been reassured that it is OK to use any encoding (including the platform default
encoding) provided the encoding is specified in the XML header, which we do.
• The following constructors were removed. Most of them had originally been added in
response to a request to provide more consistent constructors. However, now that a
richer set of properties can be defined in the LogManager configuration, this particular
set of constructors no longer makes particular sense. For example it is unlikely that
someone will create a SocketHandler and want to use the default properties except for
Formatter. People are likely to either want a default handler configuration, or to
override wider sets of the configuration properties (especially the properties that control
where output is sent).
ConsoleHandler(Formatter)
FileHandler(Formatter)
SocketHandler(Formatter)
StreamHandler(Formatter)
• Added Section 2.19 on J2EE issues. I reviewed this with the spec lead for J2EE 1.3.
• Various minor clarifications (generally in response to specification bugs filed by the
test team).
<!-- Date and time when LogRecord was created in ISO 8601 format -->
<!ELEMENT date (#PCDATA)>
<!-- The message element contains the text string of a log message. -->
<!ELEMENT message (#PCDATA)>
<!-- If the message string was localized, the key element provides
the original localization message key. -->
<!ELEMENT key (#PCDATA)>
<!-- If the message string was localized, the catalog element provides
the logger's localization resource bundle name. -->
<!ELEMENT catalog (#PCDATA)>
<!-- If the message string was localized, each of the param elements
provides the String value (obtained using Object.toString())
of the corresponding LogRecord parameter. -->
<!ELEMENT param (#PCDATA)>