Basic Logging Core Java

Every Java programmer is familiar with the process of inserting calls to System .ou t.println into troublesome code to gain insight into program behavior. Of course, once you have figuredout the cause of trouble, you remove the print statements, only to put them back inwhen the next problem surfaces. The logging API is designed to overcome this problem.

Here are the principal advantages of the API:

  • It is easy to suppress all log records or just those below a certain level, and just as easy to turn them back on.
  • Suppressed logs are very cheap, so that there is only a minimal penalty for leaving the logging code in your application.
  • Log records can be directed to different handlers, for display in the console, for storage in a file, and so on.
  • Both loggers and handlers can filter records. Filters discard boring log entries, using any criteria supplied by the filter implementor.
  • Log records can be formatted in different ways, for example, in plain text or XML.
  • Applications can use multiple loggers, with hierarchical names such as com.mycompany.myapp, similar to package names.
  • By default, the logging configuration is controlled by a configuration file. Applications can replace this mechanism if desired.

Basic Logging

Let’s get started with the simplest possible case. The logging system manages a default logger Logger.global that you can use instead of System.out. Use the info method to log an information message:

Advanced Logging

Now that you have seen “logging for dummies,” let’s go on to industrial-strength logging. In a professional application, you wouldn’t want to log all records to a single global logger. Instead, you can define your own loggers. When you request a logger with a given name for the first time, it is created.

Similar to package names, logger names are hierarchical. In fact, they are more hierarchical than packages. There is no semantic relationship between a package and its parent, but logger parents and children share certain properties. For example, if you set the log level on the logger "com.mycompany", then the child loggers inherit that level.

There are seven logging levels:

• SEVERE
• WARNING
• INFO
• CONFIG
• FINE
• FINER
• FINEST

By default, the top three levels are actually logged. You can set a different level, for example, logger. setLevel (Level.FINE);

Alternatively, you can use the log method and supply the level, such as logger .log (Level .FINE, message);

The default log record shows the name of the class and method that contain the logging call, as inferred from the call stack. However, if the virtual machine optimizes execution, accurate call information may not be available. You can use the logp method to give theprecise location of the calling class and method. The method signature is void logp(Level l, String className, String methodName, String message)

These calls generate log records of level FINER that start with the strings ENTRY and RETURN.

A common use for logging is to log unexpected exceptions. Two convenience methods include a description of the exception in the log record.

The throwing call logs a record with level FINER and a message that starts with THROW.

Changing the Log Manager Configuration

You can change various properties of the logging system by editing a configuration file.

The default configuration file is located at

To use another file, set the java.util.logging.config.file property to the file location by starting your application with java -Djava.util.logging.config.file=configFile MainClass

You can specify the logging levels for your own loggers by adding lines such as com.mycompany.myapp.level=FINE That is, append the .level suffix to the logger name. As you see later in this section, the loggers don’t actually send the messages to the console— that is the job of the handlers. Handlers also have levels. To see FINE messages on the console, you also need to set java .util .logging .Console Handler .level =FINE

It is possible to specify a different log manager by setting the java.util.logging.manager system property to the name of a subclass. Alternatively, you can keep the standardlog manager and still bypass the initialization from the logging properties file. Set thejava.util.logging.config.class system property to the name of a class that sets log managerproperties in some other way. See the API documentation for the Log Manager class formore information.

It is also possible to change logging levels in a running program by using the jconsole program.

Localization

You may want to localize logging messages so that they are readable for international users. Briefly, here are the points to keep in mind when localizing logging messages.

Localized applications contain locale-specific information in resource bundles. A resource bundle consists of a set of mappings for various locales (such as United States or Germany). For example, a resource bundle may map the string "reading-File" into strings "Reading file" in English or "Achtung! Datei wird eingelesen" in German.

A program may contain multiple resource bundles, perhaps one for menus and another for log messages. Each resource bundle has a name (such as "com.mycompany.logmessages"). To add mappings to a resource bundle, you supply a file for each locale. English message mappings are in a file com/ mycompany/ logmessages _en .properties, and German message mappings are in a file com /mycompany/ log messages _de .properties. (The en, de codes are the language codes.) You place the files together with the class filesof your application, so that the Resource Bundle class will automatically locate them.

These files are plain text files, consisting of entries such as

When requesting a logger, you can specify a resource bundle:

You often need to include arguments into localized messages. Then the message should contain placeholders {0}, {1},and so on. For example, to include the file name with a log message, include the placeholder like this:

You then pass values into the placeholders by calling one of the following methods:

Handlers

By default, loggers send records to a ConsoleHandler that prints them to the System.err stream. Specifically, the logger sends the record to the parent handler, and the ultimate ancestor (with name "") has a ConsoleHandler.

Like loggers, handlers have a logging level. For a record to be logged, its logging level must be above the threshold of both the logger and the handler. The log manager configuration file sets the logging level of the default console handler as java .util .logging .Console Handle r.level =INFO

To log records with level FINE, change both the default logger level and the handler level in the configuration. Alternatively, you can bypass the configuration file altogether and install your own handler.

By default, a logger sends records both to its own handlers and the handlers of the parent. Our logger is a child of the primordial logger (with name "") that sends all records with level INFO or higher to the console. But we don’t want to see those records twice. For that reason, we set the useParentHandlers property to false.

To send log records elsewhere, add another handler. The logging API provides two useful handlers for this purpose, a FileHandler and a SocketHandler. The SocketHandler sends records to a specified host and port. Of greater interest is the FileHandler that collects records in a file.

You can simply send records to a default file handler, like this:

The records are sent to a file javan.log in the user’s home directory, where n is a number to make the file unique. If a user’s system has no concept of the user’s home directory (for example, in Windows 95/98/Me), then the file is stored in a default location such as C:Windows. By default, the records are formatted in XML. A typical log record has the form

You can modify the default behavior of the file handler by setting various parameters inthe log manager configuration (see Table below), or by using another constructor (see theAPI notes at the end of this section).

File Handler Configuration Parameters

File Handler Configuration Parameters

You probably don’t want to use the default log file name. Therefore, you should use another pattern, such as %h/myapp.log. (See Table below for an explanation of the pattern variables.) If multiple applications (or multiple copies of the same application) use the same log file, then you should turn the “append” flag on. Alternatively, use %u in the file name pattern so that each application creates a unique copy of the log.

Log File Pattern Variables

Log File Pattern Variables

It is also a good idea to turn file rotation on. Log files are kept in a rotation sequence, such as myapp.log.0, myapp.log.1, myapp.log.2, and so on. Whenever a file exceeds the size limit, the oldest log is deleted, the other files are renamed, and a new file with generation number 0 is created.

You can also define your own handlers by extending the Handler or the StreamHandler class. We define such a handler in the example program at the end of this section. That handler displays the records in a window (see Figure below).

A log handler that displays records in a window

A log handler that displays records in a window

The handler extends the Stream Handler class and installs a stream whose write methods display the stream output in a text area.

There is just one problem with this approach—the handler buffers the records and only writes them to the stream when the buffer is full. Therefore, we override the publish method to flush the buffer after each record:

If you want to write more exotic stream handlers, extend the Handler class and define the publish, flush, and close methods.

Filters

By default, records are filtered according to their logging levels. Each logger and handler can have an optional filter to perform added filtering. You define a filter by implementing the Filter interface and defining the method

Analyze the log record, using any criteria that you desire, and return true for those records that should be included in the log. For example, a particular filter may only be interested in the messages generated by the entering and exiting methods. The filter should then call record.getMessage() and check whether it starts with ENTRY or RETURN.

To install a filter into a logger or handler, simply call the setFilter method. Note that you can have at most one filter at a time.

Formatters

The ConsoleHandler and FileHandler classes emit the log records in text and XML formats. However, you can define your own formats as well. You need to extend the Formatter class and override the method

Format the information in the record in any way you like and return the resulting string. In your format method, you may want to call the method

That method formats the message part of the record, substituting parameters and applying localization. Many file formats (such as XML) require a head and tail part that surrounds the formatted records. In that case, override the methods

Finally, call the setFormatter method to install the formatter into the handler.

A Logging Recipe

With so many options for logging, it is easy to lose track of the fundamentals. The following recipe summarizes the most common operations.

  1. For a simple application, choose a single logger. It is a good idea to give the logger the same name as your main application package, such as com.mycompany.myprog. You can always get the logger by calling
  2. For convenience, you may want to add static fields private static final Logger logger = Logger.getLogger("com.mycompany.myprog"); to classes with a lot of logging activity.

  3. The default logging configuration logs all messages of level INFO or higher to the console. Users can override the default configuration, but as you have seen, the process is a bit involved. Therefore, it is a good idea to install a more reasonable default in your application.

The following code ensures that all messages are logged to an application-specific file. Place the code into the main method of your application.

  • Now you are ready to log to your heart’s content. Keep in mind that all messageswith level INFO, WARNING, and SEVERE show up on the console. Therefore, reserve theselevels for messages that are meaningful to the users of your program. The level FINEis a good choice for logging messages that are intended for programmers.

    Whenever you are tempted to call System.out.println, emit a log message instead:

java.util.logging.Logger 1.4

  • ; Logger getLogger(String loggerName)
  • ; Logger getLogger(String loggerName, String bundleName)

gets the logger with the given name. If the logger doesn’t exist, it is created.

  • void severe(String message)
  • void warning(String message)
  • void info(String message)
  • void config(String message)
  • void fine(String message)
  • void finer(String message)
  • void finest(String message)

logs a record with the level indicated by the method name and the given message.

  • void entering(String className, String methodName)
  • void entering(String className, String methodName, Object param)
  • void entering(String className, String methodName, Object[] param)
  • void exiting(String className, String methodName)
  • void exiting(String className, String methodName, Object result)

logs a record that describes entering or exiting a method with the given parameter (s) or return value.

  • void throwing(String className, String methodName, Throwable t)

logs a record that describes throwing of the given exception object.

  • void log(Level level, String message)
  • void log(Level level, String message, Object obj
  • void log(Level level, String message, Object[] objs)
  • void log(Level level, String message, Throwable t)

logs a record with the given level and message, optionally including objects or a throwable. To include objects, the message must contain formatting placeholders {0}, {1}, and so on.

  • void logp(Level level, String className, String methodName, String message
  • void logp(Level level, String className, String methodName, String message, Object obj)
  • void logp(Level level, String className, String methodName, String message, Object[] objs)
  • void logp(Level level, String className, String methodName, String message, Throwable t)

logs a record with the given level, precise caller information, and message, optionally including objects or a throwable.

  • void logrb(Level level, String className, String methodName, String bundleName, String message)
  • void logrb(Level level, String className, String methodName, String bundleName, String message, Object obj)
  • void logrb(Level level, String className, String methodName, String bundleName, String message, Object[] objs)
  • void logrb(Level level, String className, String methodName, String bundleName, String message, Throwable t)

logs a record with the given level, precise caller information, resource bundle name, and message, optionally including objects or a throwable.

  • Level getLevel()
  • void setLevel(Level l)

gets and sets the level of this logger.

  • Logger getParent()
  • void setParent(Logger l)

gets and sets the parent logger of this logger.

  • Handler[] getHandlers()

gets all handlers of this logger.

  • void addHandler(Handler h)
  • void removeHandler(Handler h)

adds or removes a handler for this logger.

  • boolean getUseParentHandlers()
  • void setUseParentHandlers(boolean b)

gets and sets the “use parent handler” property. If this property is true, the logger forwards all logged records to the handlers of its parent.

  • Filter getFilter()void setFilter(Filter f)

gets and sets the filter of this logger.

  • abstract void publish(LogRecord record)

sends the record to the intended destination.

java.util.logging.Handler 1.4

  • abstract void flush()

flushes any buffered data.

  • abstract void close()

flushes any buffered data and releases all associated resources.

  • Filter getFilter()
  • void setFilter(Filter f)

gets and sets the filter of this handler.

  • Formatter getFormatter()
  • void setFormatter(Formatter f)

gets and sets the formatter of this handler.

  • Level getLevel()
  • void setLevel(Level l)

gets and sets the level of this handler

java.util.logging.Handler 1.4

  • ConsoleHandler()

constructs a new console handler.

java.util.logging.FileHandler 1.4

  • FileHandler(String pattern)
  • FileHandler(String pattern, boolean append
  • FileHandler(String pattern, int limit, int count)
  • FileHandler(String pattern, int limit, int count, boolean append)

constructs a file handler.

java.util.logging.LogRecord 1.41

  • Level getLevel()

gets the logging level of this record.

  • String getLoggerName()

gets the name of the logger that is logging this record.

  • ResourceBundle getResourceBundle()
  • String getResourceBundleName()

gets the resource bundle, or its name, to be used for localizing the message, or null if none is provided.

  • String getMessage()

gets the “raw” message before localization or formatting.

  • Object[] getParameters()

gets the parameter objects, or null if none is provided.

  • Throwable getThrown()

gets the thrown object, or null if none is provided.

Parameters: pattern The pattern for constructing the log file name. See Table belowfor pattern variables. limit The approximate maximum number of bytes before a new log file is opened. count The number of files in a rotation sequence. append true if a newly constructed file handler object should append to an existing log file.

  • String getSourceClassName()
  • String getSourceMethodName()

gets the location of the code that logged this record. This information may be by the logging code or automatically inferred from the runtime stack. It might be inaccurate, if the logging code supplied the wrong value or if the running code was optimized and the exact location cannot be inferred.

  • long getMillis()

gets the creation time, in milliseconds, since 1970.

  • long getSequenceNumber()

gets the unique sequence number of this record.

  • int getThreadID()

gets the unique ID for the thread in which this record was created. These IDs are assigned by the LogRecord class and have no relationship to other thread IDs.

java.util.logging.Filter 1.4

  • boolean isLoggable(LogRecord record)

returns true if the given log record should be logged.

java.util.logging.Formatter 1.4

  • abstract String format(LogRecord record)

returns the string that results from formatting the given log record.

  • String getHead(Handler h)
  • String getTail(Handler h)

returns the strings that should appear at the head and tail of the document containing the log records. The Formatter superclass defines these methods to return the empty string; override them if necessary.

  • String formatMessage(LogRecord record)

returns the localized and formatted message part of the log record.



Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Core Java Topics