View
27
Download
0
Category
Preview:
Citation preview
The Java Logging APIand Lumberjack
Copyright © 2001 Brian R. Gilstrap
Please
• Turn off audible ringing of cell phones/pagers• Take calls/pages outside
Copyright © 2001 Brian R. Gilstrap
About this talk
• Discusses the Java Logging API• Discusses Lumberjack• Does not discuss log4j
– Another open source logging library
• Does not compare log4j to the Java Logging API– I don't know log4j
• Can't tell you which is better for your situation
– The two API's seem pretty similar
Please don't try to engage me in an argument about which is better,log4j or Java Logging :-)
Copyright © 2001 Brian R. Gilstrap
Overview - what is Java Logging?
• First introduced in Java Specification Request (JSR) 47– Title: “Logging API Specification”– Description: Define standard logging APIs for the error and trace logging.
• Included in JDK 1.4 (currently in late beta)• Free implementation for JDK 1.2/1.3 available
– Called Lumberjack– Available from http://javalogging.sourceforge.net
• Designed for messages related to– Program debugging– Error reporting– General diagnostics
Copyright © 2001 Brian R. Gilstrap
Overview (cont)
• A Java Class Library Designed to be:* Simple to use* Fast
– Leave logging code in production executable* Configurable
– Suppress generation of records that are not of interest* Flexible
– Provide a number of common output formats* Extensible* Usable out-of-the-box
– Default configuration - can be overridden– Default set of handlers
Copyright © 2001 Brian R. Gilstrap
Overview (cont)
• Dynamically configurable at runtime:– Change what gets logged
• Levels• Filters
– Change where log records are output• Handlers
– Change output format• Formatters
• Extensible classes/interfaces include:– Level– Filter– Handler– Formatter– LogManager
Copyright © 2001 Brian R. Gilstrap
Basic Architecture
Logger Handler
Filter Filter Formatter
Outside WorldApplication
Copyright © 2001 Brian R. Gilstrap
Level
• Indicates the importance of a record• Used to perform a quick filter to weed out
irrelevant messages• Standard levels:
– SEVERE (most important)– WARNING– INFO– CONFIG– FINE– FINER– FINEST (least important)
Copyright © 2001 Brian R. Gilstrap
Logger
• Used to generate logging messages• Do preliminary filtering of messages
– Only those of high enough importance actually logged• Can use a Filter to further filter records• Can have Handlers attached to handle records• Generally have a name
– Can have anonymous loggers, but not generally used.• If record is not filtered, forwards record to parent
Loggers' Handlers– Can be turned off
Logger Handler
Filter Filter Formatter
Outside WorldApplication
Copyright © 2001 Brian R. Gilstrap
Logger (cont)
• Created or retrieved via a static method:
public static Logger getLogger( String aName );
Logger awtLogger = Logger.getLogger( "java.awt" );
• Assures only one Logger with a given name in a VM.– Two pieces of code that ask for a Logger with the same
name will share the same Logger object.
Copyright © 2001 Brian R. Gilstrap
Logger Methods
• General logging methods– boolean isLoggable( Level aLevel )
• Perform filtering check– void log( Level l, …
• No class and method names specified– void logp( Level l,
String sourceClass,String sourceMethod, …
• Class name and method name– void logrb( Level l,
String sourceClass,String sourceMethod,String rsrcBundle, …
• Class name, method name, and resource bundle (internationalization)
…, String aMessage )…, String aMessage, Object param )…, String aMessage, Object[] params )
Copyright © 2001 Brian R. Gilstrap
Logger Methods (cont)
• Convenience methods– entering(...) (message == "ENTRY"; Level == FINER)
– exiting(...) (message == "RETURN"; Level == FINER)
– fine(…)– finer(…)– finest(…)– info(…)– severe(…)– warning(…)
– caught( Level l, Throwable t );– throwing( Level l, Throwable t );
( String aMessage )( String aMessage, Object param )( String aMessage, Object[] params )
( String aMessage, Object param )( String aMessage, Object[] params )
Copyright © 2001 Brian R. Gilstrap
Logger Methods (cont)
• Configuration– public Level getLevel();
– public setLevel( Level aLevel );
– public Filter getFilter()– public setFilter( Filter aFilter );
– public Handler[] getHandlers();
– public addHandler( Handler aHandler );
– public removeHandler( Handler aHandler );
– public boolean getUseParentHandlers();– public setUseParentHandlers( booleanuseParentHandlers );
Copyright © 2001 Brian R. Gilstrap
A Simple Example
public class HelloWorld {
private static Logger theLogger =
Logger.getLogger( HelloWorld.class.getName() );
public static void main( String[] args ) {
HelloWorld hello = new HelloWorld( "Hello Everybody!" );
hello.sayHello();
}
private String theMessage;
public HelloWorld( String message ) {
theMessage = message;
}
public void sayHello() {
theLogger.info( HelloWorld.class.getName(), "sayHello" theMessage );
}
}
Copyright © 2001 Brian R. Gilstrap
Logger Hierarchy
• Organized by name• Pieces of the names are separated by dots ('.')• Follow the package naming of the Java
Classes–e.g. java.util.logging…
• Root Logger– Name is the empty string– Root of Logger tree
• Names can be for packagesand not just classes– java.util
""
net java
Sourceforge.javalogging util
installer testhello
Root Logger
Copyright © 2001 Brian R. Gilstrap
Logger Hierarchy (cont)
• Loggers with no Level inherit from immediate parent.
• net.sourceforge.javalogging.installer.Installer would inherit from:– net.sourceforge.javalogging.installer
– net.sourceforge.javalogging– net.sourceforge– net– "" (Root Logger)
Copyright © 2001 Brian R. Gilstrap
Logger Hierarchy (cont)
• Examples:
net.sourceforge.javalogging.installer.Installer == null
net.sourceforge.javalogging == INFO
net.sourceforge == WARNING
Effective level is INFO
net.sourceforge.javalogging.installer.Installer == null
net.sourceforge.javalogging == null
net.sourceforge == WARNING
Effective level is WARNING
Effective level is WARNING
Copyright © 2001 Brian R. Gilstrap
Logger Hierarchy (cont)
• Loggers forward records to parents' Handlers• No further Logger checks are made
– Record goes directly to the Handlers of each parent in the chain• Filters attached to a Handler may still filter record
Net.sourceforge.javalogging.installer.Installer
net.sourceforge
net
Handler
Handler
Call to Logger
1
FilterHandler
10
Passes Level check
Outside world
Outside world
No level check
No level checkFilter does not pass8
7
54
6
23
9
Copyright © 2001 Brian R. Gilstrap
Anonymous loggers
• Have no name• Their parent is the Root Logger
– By default their messages go to any handlers attached to the Root Logger
• Do not affect other Loggers• Generally only used by things like
applets
Copyright © 2001 Brian R. Gilstrap
The "global" logger
• Static field of the Logger class– public static final Logger global = Logger.getLogger( "global" );
• Has name “global”• Root Logger is its parent• Intended for "casual" use of the Logging API.
Copyright © 2001 Brian R. Gilstrap
LogRecord
• Contains the message plus some additional information
• Not generated until Logger level test is passed–Must be >= Logger Level
• Can be created by programmer directly
Copyright © 2001 Brian R. Gilstrap
LogRecord - Highlights
• Level - level of message• Logger name - name of logger that created the record• Message - the message passed to the logger• Millis - when record was generated (in milliseconds)• Parameters - any parameters specified to the Logger• Seq # - a unique sequence number for the record• Source class name - name of class whose code called Logger
– Guessed if not specified– Guess is not always right
• Source method name - name of method which called the Logger– Guessed if not specified– Guess is not always right
• Thrown - any Throwable (exception) that was provided
Copyright © 2001 Brian R. Gilstrap
LogManager
• Singleton– LogManager.getLogManager();
• Used to bootstrap logging• Keeps track of all named Loggers• Reads a configuration file when created
– JRE lib/logging.properties– Change file read by setting java.util.logging.config.file property
• Can be sub-classed for special-purposes– EJB Containers– Custom behavior– Etc.
Copyright © 2001 Brian R. Gilstrap
logging.properties
• Read by LogManager• System Properties are defaults
– Useful for setting logging properties using java -D...• Values retrieved via LogManager's getProperty() method
• Java Properties file.• Lives in $JAVA_HOME/lib/logging.properties
– JRE lib directory
Copyright © 2001 Brian R. Gilstrap
logging.properties contents
• *.level - any property ending in '.level' is assumed to specify a logging Level for some Logger– net.sourceforge.javalogging.installer.Installer=FINER– java.util.level=ERROR– ".level" - used to specify the Level for the Root Logger– etc.
• "handlers" - defines a whitespace separated list of class names– Classes to load and register as Handlers on the root Logger– Must extend Handler
• Properties for specific logging classes (more later)
Copyright © 2001 Brian R. Gilstrap
logging.properties contents (cont)
• "config" - defines a whitespace separated list of class names– Intended to allow arbitrary configuration code to be run.– One new instance will be created for each class named
• using default constructor (no args)• constructor must be public
– Constructor may execute arbitrary code• update the logging configuration
– setting logger levels– adding handlers– adding filters– etc.
• perform other initialization
• All Handlers and Config classes must be on the bootstrapclasspath.
Copyright © 2001 Brian R. Gilstrap
Handlers
• Process LogRecords• Can do anything with the record
– Typically send it outside the program– Can do other things (e.g. MemoryHandler)
• Have their own Level– LogRecords with too low a level won't be output
• Can have a Filter– After Level test, must also pass Filter to be output
Logger Handler
Filter Filter Formatter
Outside WorldApplication
Copyright © 2001 Brian R. Gilstrap
Handlers (cont)
• Handlers get properties from LogManager– LogManager gets them from logging.properties
• Can have more than one Handler attached to the same Logger
Logger
Handler
Application Handler
Handler
Copyright © 2001 Brian R. Gilstrap
Handlers (cont)
• Each Handler is asked to handle the LogRecord• Order in which Handlers are called is not specified
– Don't assume a particular order
Logger
Handler
Application Handler
Handler
Copyright © 2001 Brian R. Gilstrap
java.util.logging.ConsoleHandler
• Sends output to standard error
• java.util.logging.ConsoleHandler.level– Level for Handler (default: Level.INFO)
• java.util.logging.ConsoleHandler.filter– Name of Filter (default: no Filter)
• java.util.logging.ConsoleHandler.formatter– Name of Formatter (default: SimpleFormatter)
• java.util.logging.ConsoleHandler.encoding – Character set encoding (default: default platform encoding)
Copyright © 2001 Brian R. Gilstrap
java.util.logging.FileHandler
• Sends output to a file or cycles through a collection of files• java.util.logging.FileHandler.level
– Level for Handler (default: Level.ALL)
• java.util.logging.FileHandler.filter – Name of Filter (default: no Filter)
• java.util.logging.FileHandler.formatter – Name of Formatter (default: XMLFormatter)
• java.util.logging.FileHandler.encoding– Character set encoding (default: default platform encoding)
• java.util.logging.FileHandler.limit – Maximum file size (bytes) (default: 0 => no limit).
Copyright © 2001 Brian R. Gilstrap
FileHandler Properties (cont)
• java.util.logging.FileHandler.count– # output files (default: 1)
• java.util.logging.FileHandler.append– Append onto existing files (default: false)
• java.util.logging.FileHandler.pattern– Pattern for generating the output file name (default:
"%h/java%u.log")
Copyright © 2001 Brian R. Gilstrap
java.util.logging.FileHandler.pattern
• Supports several special components replaced at runtime"/" - Replaced by the local pathname separator"%t" - System temporary directory
• /tmp• C:\temp• etc.
"%h" - Value of the "user.home" system property"%g" - Generation number to distinguish rotated logs
• Starts with 0• If not specified and file count > 1, ".%g" is added to pattern
automatically"%u" - Unique number to resolve conflicts between multiple
Java programs"%%" - Literal percent sign "%"
Copyright © 2001 Brian R. Gilstrap
java.util.logging.SocketHandler• Sends output through a socket• java.util.logging.SocketHandler.level
– Level for Handler (default: Level.ALL)
• java.util.logging.SocketHandler.host – Host to send to (default: no default)
• java.util.logging.SocketHandler.port – TCP port to use (default: no default)
• java.util.logging.SocketHandler.filter – Name of Filter (default: no Filter)
• java.util.logging.SocketHandler.formatter – Name of Formatter (XMLFormatter)
• java.util.logging.SocketHandler.encoding – Character set encoding (default: default platform encoding)
Copyright © 2001 Brian R. Gilstrap
java.util.logging.MemoryHandler
• Circular ("ring") buffer of LogRecords– Holds N most recent records until triggered to push them
to another handler– When buffer filled, new records cause oldest record to be discarded
• Doesn't format its own records• Has a level called the "push level"• Forwards records to another handler whenever push is called
– An incoming LogRecord's Level meets the push level• default push level is Level.SEVERE
– push is called explicitly.– A subclass overrides log method and calls push on some condition.
Logger Handler Outside WorldMemoryHandler
LogRecords
Copyright © 2001 Brian R. Gilstrap
java.util.logging.MemoryHandler (cont)
• java.util.logging.MemoryHandler.level – Level for Handler (default: Level.ALL)
• java.util.logging.MemoryHandler.filter – Name of Filter (default: no Filter)
• java.util.logging.MemoryHandler.size– Buffer size (in records) (default: 1000)
• java.util.logging.MemoryHandler.push– PushLevel (default: level.SEVERE)
• java.util.logging.MemoryHandler.target– Target Handler class (default: no default)
Copyright © 2001 Brian R. Gilstrap
Formatters
• Format LogRecords for output• Supports notion of a head and tail
– Head gets printed at the start of the file– Tail gets printed at the end of the file– Can be null
• Can be attached to any Handler• Two Standard formatters
– SimpleFormatter– XMLFormatter
Logger Handler
Filter Filter Formatter
Outside WorldApplication
Copyright © 2001 Brian R. Gilstrap
java.util.logging.SimpleFormatter
• Prints a brief textual representation of a LogRecord• Has no head or tail
Nov 27, 2001 02:26:04 PM net.sourceforge.javalogging.test.HelloWorld sayHello INFO: Hello Everybody!
Copyright © 2001 Brian R. Gilstrap
java.util.logging.XMLFormatter
• Creates an XML document for a set of records• Has a head
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE log SYSTEM "logger.dtd"><log>
• Has a tail</log>
• Each LogRecord produces a <record> element
Copyright © 2001 Brian R. Gilstrap
java.util.logging.XMLFormatter Output
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
<date>2001-11-27T12:38:52</date>
<millis>1006886332546</millis>
<sequence>3244</sequence>
<logger>com.foo</logger>
<level>INFO</level>
<class>com.foo.TestXMLFormatter</class>
<method>writeARecord</method>
<thread>15</thread>
<message>Hello world!</message>
</record>
</log>
Copyright © 2001 Brian R. Gilstrap
java.util.logging.Filter
• Interface– One method– boolean isLoggable(LogRecord record)
• Returns true if the LogRecord should be logged/handled.• Can be attached to Loggers and Handlers• No pre-built filters
Logger Handler
Filter Filter Formatter
Outside WorldApplication
Copyright © 2001 Brian R. Gilstrap
java.util.logging.ErrorManager
• Won't use unless you are implementing a Handler• Used by Handlers to report problems
– public void error( String msg, Exception ex,int code );
– Default behavior is to write a message to standard error• Has some predefined codes to indicate the nature of
the problem– CLOSE_FAILURE– FLUSH_FAILURE– FORMAT_FAILURE– GENERIC_FAILURE– OPEN_FAILURE– WRITE_FAILURE
Copyright © 2001 Brian R. Gilstrap
Extending the Framework
• Custom Levels– For new levels of importance– Need to take care to fit into existing Levels– Done as part of ESI Event Logging tie-in
• Custom Filters - allow for other criteria– Time of day, day of week, etc.– Contents of message– Any field of LogRecord– Etc.
• Custom Handlers• Custom Formatters• Custom LogManager
Copyright © 2001 Brian R. Gilstrap
Lumberjack
• Open Source (LGPL) implementation of Java Logging API
• Home Page: javalogging.sourceforge.net• Written by Brian Gilstrap
– Contributors welcome– Bug reports welcome
Copyright © 2001 Brian R. Gilstrap
Using Lumberjack with JDK 1.2/1.3
• Provides logging API for JDK 1.2 & 1.3• Get Lumberjack
– Download from javalogging.sourceforge.net– Unpack JAR– Run installer
Copyright © 2001 Brian R. Gilstrap
Installing Lumberjack– java -jar logging.jar– Brings up a GUI that installs Lumberjack
– Checks to make sure it's compatible with your JRE• Won't install on top of 1.4's implementation• Won't install into a JDK < 1.2
Copyright © 2001 Brian R. Gilstrap
Installing Lumberjack (cont)– Asks if you want to overwrite any existing installation
– Even if you overwrite, also asks if you want to overwrite any existing logging.properties
– Requires that you have permission to alter the JRE directories
Copyright © 2001 Brian R. Gilstrap
Using Lumberjack without installing(no permissions or on MacOS X)
• Put logging.jar on your bootstrap classpath-Xbootclasspath/a:$HOME/Library/logging.jar
• Put logging.properties into JRE lib/System/Library/Frameworks/JavaVM.framework/Home/lib
• This is ugly– I'm working to make the GUI work on MacOS X too– Can't give you permissions to alter JRE directories :-)
Copyright © 2001 Brian R. Gilstrap
A Few Statistics
• java.util.logging – 16 Source files– 2924 lines of code– 20 Classes (including nested classes)
• net.sourceforge.javalogging.installer– 2 Source files– 242 lines of Code– 5 Classes (including nested classes)
• logging.jar– 50163 bytes– 18 Source files– 3166 lines of Code
Copyright © 2001 Brian R. Gilstrap
The Dodgy Bitsareas where Lumberjack is currently weak or non-comformant
• Resource Bundles (fixable)
– Doesn't implement latest spec: search order to find resource bundles– Any resource bundle guru's want to vett the code?
• FileHandler (fixable)
– Has a number of open bugs
• Source class and method guessing (not fixable?)
– Slow (requires parsing stack trace generated from a Throwable)– 1.4 has a StackFrame API that should make it much faster (need to
measure)
• Serialization of LogRecord exception (not fixable?)
– 1.4 Serialization of a Throwable includes any stack trace– 1.3 & prior do not– Can't do RMI between 1.4 & earlier systems involving LogRecords
Copyright © 2001 Brian R. Gilstrap
References
• JSR 47 (the Logging API specification)– http://jcp.org/jsr/detail/47.jsp
• JDK 1.4 beta 3 documentation of Logging– http://java.sun.com/j2se/1.4/docs/guide/util/logging/index.ht
ml– http://java.sun.com/j2se/1.4/docs/guide/util/logging/overview
.html– http://java.sun.com/j2se/1.4/docs/api/java/util/logging/packag
e-summary.html• Project page for Lumberjack
– http://javalogging.sourceforge.net/• Article on the Logging API
– http://www.ociweb.com/jnb/jnbJun2001.html
Copyright © 2001 Brian R. Gilstrap
Thanks
Please use Lumberjack, that's why I wrote it :-)
Recommended