Wednesday, 10 June 2009

Console,Text and XML Logger Output with java.util.logging.Logger

Enhancing the previous blog "Getting Started with java.util.logging.Logger", this example looks at the next step, to output different message levels to the console than to file and shows how to output text or xml.

The logging levels are:

SEVEREThe highest value; intended for extremely important messages (e.g. fatal program errors).
WARNINGIntended for warning messages.
INFOInformational runtime messages.
CONFIGInformational messages about configuration settings/setup.
FINEUsed for greater detail, when debugging/diagnosing problems.
FINEREven greater detail.
FINESTThe lowest value; greatest detail.

So an example would look something like this:

ackage com.wownow;

import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.logging.XMLFormatter;

public class MyLoggingTest2 {

public static void main(String[] args) throws IOException {

Level consoleLogLevel = Level.CONFIG;
Level defaultLogLevel = Level.FINER;

ConsoleHandler ch = new ConsoleHandler();

FileHandler txtfh = new FileHandler("MyLogFile.txt");
txtfh.setFormatter(new SimpleFormatter());

FileHandler xmlfh = new FileHandler("MyLogFile.xml");
xmlfh.setFormatter(new XMLFormatter());

Logger logger = Logger.getLogger("MyLogger");


logger.severe("My Severe Message");
logger.warning("My Warning Message");"My Info Message");
logger.config("My Config Message");
logger.fine("My Fine Message");
logger.finer("My Finer Message");
logger.finest("My Finest Message");




In this example we:

  • Create two level variables,one for the console and one for the files

  • Then create a console handler, and set the level of this handler, in the case to "CONFIG"

  • We then create a handler for the text file, set its formatter to SimpleFormatter, so the output is in plain text, then set its level

  • Then we create a third handler for the xml and set its formater to XMLFormatter (this could be ommitted as it's the default), and again set its level

  • The logger object is then created, we use setUseParentHandlers to false to stop duplicated messages appearing on the console

  • The logger level is set, this assumes the defaultLogLevel is lower than the consoleLogLevel, otherwise you could use Level.ALL

  • Next the three handlers are added to the logger

  • Next we output a message for each logging level. Only the messages above the level "CONFIG" will be output to the console or "FINER" written to the file.

  • We then close the file handlers.

My Done Message

No comments: