|
Welcome to the Java Developer Connection Java Technology Fundamentals Newsletter.
This monthly newsletter provides a way for you to learn the basics of the Java programming language, discover new resources,
and keep up-to-date on the latest additions to Sun Developer Network's New to Java Programming Center.
You can receive future issues of this newsletter in HTML or text.
For more Java technology content, visit these sites:
java.sun.com - The Java technology source for developers. Get the latest Java platform releases, tutorials, newsletters and more.
java.net - A web forum where enthusiasts of Java technology can collaborate and build solutions together.
java.com - The ultimate marketplace promoting Java technology, applications and services.
Java Programming Language Basics
Java Logging API Basics
New to the Java 2 Platform, Standard Edition, verison 1.4, the
java.util.logging package offers the Java Logging API. This
logging facility allows you to embed messages inside your code,
and configure at runtime whether or not the mesages should be
displayed or logged. If you don't need the information all the time,
turn it off, and enable it when the user needs it (or you need it
to get debug output from the user). Want to control the level of
messages logged such that you only want serious logging messages
from a particular package? This too is configurable.
In the simplest case, you get the logger and log the message:
- Get the Logger for the currrent package
Logger logger = Logger.getLogger(packageName);
- Log your message
logger.log(level, text, exception)
To demonstrate, the following program logs a severe message:
package com.sun.java;
import java.util.logging.*;
public class LogSample {
private static Logger logger =
Logger.getLogger("com.sun.java");
public static void main(String args[]) {
logger.log(Level.SEVERE, "Testing - Level = SEVERE");
}
}
First, compile the program. Since the program is in a package, be
sure to use the -d option to send the .class file to the appropriate
subdirectory:
javac -d . LogSample.java
Then, run the program:
java com.sun.java.LogSample
By default, logging output goes to the console. Depending upon when
you run the program, you'll get an appropriate time stamp.
May 15, 2004 9:08:33 AM com.sun.java.LogSample main
SEVERE: Testing - Level = SEVERE
The reason you get the Logger for a particular package is so that you can enable or disable logging for a particular package. Before we look at that though, let us explain the logging levels, of which there are seven.
- SEVERE
- WARNING
- INFO
- CONFIG
- FINE
- FINER
- FINEST
By having different logging levels, you can control when a message
is logged and the level of detail. So, for a SEVERE-level message,
you might dump a stack trace at a location where the program
shouldn't get to under normal circumstances. For INFO-level, you
might have entry / exit from methods. And, FINEST-level might be
as each line is executed. There is no hard definition of what each
level must print out. It is completely up to you during your
development. There is a small amount of overhead to test if the
current logging level is enabled for the given package, but
having the logging information available during testing allows a
better level of debug information to come back to the development
team from say a quality assurance (QA) or user testing group.
There's much more to the logging facility than just saying, here's
a message, log it. For instance, to send out to a file, use a
FileHandler:
package com.sun.java;
import java.util.logging.*;
import java.io.*;
public class LogSample2 {
private static Logger logger =
Logger.getLogger("com.sun.java");
public static void main(String args[]) throws IOException {
FileHandler fh = new FileHandler("log.out");
// Send logger output to FileHandler.
logger.addHandler(fh);
// Log all
logger.setLevel(Level.ALL);
logger.log(Level.FINE, "Testing - Level = FINE");
}
}
This sends the log message to the file log.out, as XML.
<?xml version="1.0" encoding="windows-1252" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
<date>2004-05-26T09:41:20</date>
<millis>1085578880859</millis>
<sequence>0</sequence>
<logger>com.sun.java</logger>
<level>FINE</level>
<class>com.sun.java.LogSample2</class>
<method>main</method>
<thread>10</thread>
<message>Testing - Level = FINE</message>
</record>
</log>
The system also provides other handlers, like the MemoryHandler for
storing the last 'n' records, without worrying about formatting
until you wish to display / save. Through constructive use of the
logging facility, you can better maintain and service all your
software. For additional information on the available APIs, see the
Java Logging Overview document.
Java Bits
Chapters from Murach's Java Servlets and JSP
by Andrea Steelman and Joel Murach
Last month you had an introduction to JavaServer Pages (JSP)
technologies, and you learned to create an online quiz. If you
want to learn more about using JSP pages and want a book to get
you going, consider Murach's Java Servlets and JSP by Andrea
Steelman and Joel Murach.
Murach's Java Servlets and JSP is designed for the programmer who
has experience with the Java programming language, but is new to
developing web applications. It provides hands-on experience while
you learn the skills necessary to develop server-side applications
at a professional level. In addition, the bound-in CD contains
the software and source code presented in the book.
Read two sample chapters on java.sun.com
Making Sense of the Java Class
Format Class
Format is an abstract class for formatting locale-sensitive
information such as dates, messages, and numbers.
Format defines the programming interface for formatting
locale-sensitive objects into Strings (the format method), and for
parsing Strings back into objects (the parseObject method).
A parseObject method parses any string formatted by its format
method. However, there may be exceptional cases where this is not
possible. For example, a format method might create two adjacent
integer numbers with no separator in between, and in this case the
parseObject could not tell which digits belong to which number.
Subclassing
The Java 2 platform provides three specialized subclasses of Format:
DateFormat, MessageFormat, and NumberFormat.
Concrete subclasses must implement three methods:
-
format(Object obj, StringBuffer toAppendTo, FieldPosition pos)
-
formatToCharacterIterator(Object obj)
-
parseObject(String source, ParsePosition pos)
These general methods allow polymorphic parsing and formatting of
objects and are used, for example, by MessageFormat. Subclasses
often also provide additional format methods for specific input
types as well as parse methods for specific result types. Any
parse method that does not take a ParsePosition argument should
throw ParseException when no text in the required format is at
the beginning of the input text.
Most subclasses will also implement the following factory methods:
-
getInstance for getting a useful format object appropriate
for the current locale
-
getInstance(Locale) for getting a useful format object
appropriate for the specified locale
In addition, some subclasses may also implement other getXxxxInstance
methods for more specialized control. For example, the NumberFormat
class provides getPercentInstance and getCurrencyInstance methods
for getting specialized number formatters.
Subclasses of Format that allow programmers to create objects for
locales (with getInstance(Locale) for example) must also implement
the following class method:
public static Locale[] getAvailableLocales()
And finally, subclasses may define a set of constants to identify
the various fields in the formatted output. These constants are
used to create a FieldPosition object which identifies what
information is contained in the field and its position in the
formatted result. These constants should be named item_FIELD
where item identifies the field. For examples of these constants,
see ERA_FIELD and its friends in DateFormat.
From the Java API Documentation
Test what you learned in this article about logging
Program Challenge
Using the Logging API, create a logging Handler that sends logged
messages to a separate window. Demonstrate the handler in a simple
test program.
See a possible solution
Sun's Web Courses
Programming With the Java 3D API: A Technical Overview
This course presents basic concepts and key features of the
Java 3D API. It also discusses a graphics programming paradigm,
providing an overview of creating visual three-dimensional (3D)
objects and features to be applied, such as lighting, shading,
animation, user navigation and interaction within a 3D scene.
As a powerful component of Java Media Technologies, the Java 3D
API extends the Java Programming language to the 3D graphics
world.
Find out more
Sun's Instructor Led Courses
Java Programming Language for Visual Basic Programmers
The Java Programming Language for Visual Basic Programmers course
provides students with an in-depth introduction to object-oriented
programming concepts and the fundamentals of the Java programming
language. Students learn to construct basic Java technology
applications using a variety of object-oriented techniques.
Find out more
2004 JavaOne Conference and Article
Moscone Center, San Francisco, California
JavaOne, Sun's 2004 Worldwide Java Developer Conference
June 28 - July 1, 2004
Moscone Center, San Francisco, California
The JavaOne conference is less than a month away. Hundreds of
in-depth technical and Birds-of-a-Feather sessions, interactive
Hands-on Labs, visionary General Session presentations, and the
Java University program equip you with the skills, solutions,
and knowledge you need to be efficient and successful in your role
as a Java technology professional.
For More Information
Downloading the Java 2 Platform
For most Java development, you need the class libraries, compiler, tools, and runtime environment provided with the J2SE development kit.
Find archived issues of the following Java technology developer newsletters or manage your current newsletter subscriptions: https://softwarereg.sun.com/registration/developer/en_US/subscriptions
Subscribe to the following newsletters for the latest information about technologies and products in other Java platforms:
- Core Java Technologies Newsletter. Learn about new products, tools, resources, and events of interest to developers working with core Java technologies.
- Wireless Developer Newsletter. Learn about the latest releases, tools, and resources for developers working on wireless and Java Card technologies and applications.
- Core Java Technologies Tech Tips (formerly JDC Tech Tips) Get expert tips, sample code solutions, and techniques for developing in the Java 2 Platform, Standard Edition (J2SE)
You can subscribe to these and other JDC publications on the JDC Newsletters and Publications
page
PRIVACY STATEMENT:
Sun respects your online time and privacy. You have received this based on your e-mail preferences. If you would prefer not to receive this information, please follow the steps at the bottom of this message to unsubscribe.
IMPORTANT: Please read our Terms of Use, Privacy, and Licensing policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/
http://developer.java.sun.com/berkeley_license.html
Copyright 2004 Sun Microsystems,
Inc. All rights reserved. 4150 Network Circle, Santa Clara, CA 95054
FEEDBACK
Comments? Send your feedback on the Java Technology Fundamentals Newsletter to: dana.nourie@sun.com
SUBSCRIBE/UNSUBSCRIBE
- To subscribe, go to the subscriptions page, choose the newsletters you want to subscribe to and click Update
- To unsubscribe, go to the subscriptions page, uncheck the appropriate check box, and click Update
Trademark Information: http://www.sun.com/suntrademarks/
Java, J2EE, J2SE, J2ME, and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.
|