LoggingWhat is logging?Why use logging?Basic useLogging levels and methodsControlling logging levelsAdditional Logger methodsLogging flow of controlFiltersLogging formatting and destinationsUsing a FileHandlerFileHandler resultsReading log filesWhat to logWhen logging goes badThe rest of the storyThe EndJan 14, 2019LoggingWhat is logging?“Logging” is producing messages that tell you what your program is doingIt’s not much different than using System.out.println(...)Log messages can go to the console, to a file, or one of several other places (e.g. sent over the Internet)You can use logging to help you debug a programYou can use logging to produce a file when the user runs your programWhy use logging?Reality: Large programs always have bugsJUnit testing can greatly reduce this problem, but it’s impossible to see in advance all potentially useful testsYour program may go to customers (users)Typical error report from customer: “It doesn’t work.”We love it when we have a customer who tries assorted things and gives us a detailed scenario in which the program failsSuch customers are rareHere’s what you want to tell the typical customer:“Send us the log; it’s in such-and-such a place.”Basic useimport java.util.logging.*;private static Logger myLogger = Logger.getLogger("myPackage");myLogger.log(Level.SEVERE, "Bad news!");Aug 15, 2004 10:51:09 AM myPackage.Sync mainSEVERE: Bad news!Logging levels and methodsLevel.SEVERELevel.WARNINGLevel.INFOLevel.CONFIGLevel.FINELevel.FINERLevel.FINESTThese levels are ordered, so that you can set the level of severity that results in log messagesHowever, the levels have no inherent meaning--they are what you make of themmyLogger.severe(String msg);myLogger.warning(String msg);myLogger.info(String msg);myLogger.config(String msg);myLogger.fine(String msg);myLogger.finer(String msg);myLogger.finest(String msg);Controlling logging levelspublic void Logger.setLevel(Level newLevel)Sets the logger to log all messages at newLevel or aboveLogger calls at lower levels don’t do anythingExample: logger.setLevel(Level.WARNING);Additional settings:logger.setLevel(Level.ALL);logger.setLevel(Level.OFF);public Level getLevel()Note that this returns a Level, not an intLevel has intValue() and toString() methodsAdditional Logger methodsvoid entering(String:sourceClass, String:sourceMethod)void entering(String:sourceClass, String:sourceMethod, Object:para m1)void entering(String:sourceClass, String:sourceMethod, Object[]:params)void exiting(String:sourceClass, String:sourceMethod)void exiting(String:sourceClass, String:sourceMethod, Object:result)These log messages at level FINERLogging flow of controlYou send your message to a LoggerThe Logger checks a Filter to see whether to ignore the messageThe Logger sends the message to a Handler to put the message somewhereThe Handler checks another Filter to see whether to ignore this kind of message sent to this destinationThe Handler calls a Formatter to decide what kind of a text string to produceThe Handler sends the formatted message somewhereLoggerHandlerFilterFilterFormatterapplication destinationFiltersFilter is an interface; it defines the single methodboolean isLoggable(LogRecord record )A LogRecord is another class in java.util.logging; it provides numerous methods for examining the proposed logging messageWe won’t go into the details of LogRecord in this lecture (see the API if you need to use this)Logging formatting and destinationsThe JDK defines five Handlers:StreamHandler: sends messages to an OutputStreamConsoleHandler: sends messages to System.err (default)FileHandler: sends messages to a fileSocketHandler: sends messages to a TCP portMemoryHandler: buffers messages in memoryIt also defines two ways to format messages:SimpleFormatter (default)XMLFormatterAnd, of course, you can define your own Handlers and FormattersAs you can tell from the “Basic Use” slide earlier, you can ignore all of this and just use the defaultsUsing a FileHandlertry { logger.addHandler(new FileHandler("myLogFile"));}catch (SecurityException e) { e.printStackTrace();}The default Formatter for a FileHandler is XMLFormatterFileHandler results<?xml version="1.0" encoding="MacRoman" standalone="no"?><!DOCTYPE log SYSTEM "logger.dtd"><log><record> <date>2004-08-15T13:21:26</date> <millis>1092590486248</millis> <sequence>0</sequence> <logger>myPackage</logger> <level>SEVERE</level> <class>myClass</class> <method>main</method> <thread>10</thread> <message>Bad news!</message></record></log>Reading log filesDon’t like XML? See the SimpleFormatter classWhen you log, your log messages must be exceptionally easy to understandRemember, you might see a log file months or even years after you wrote the programMessages such as at1: 12 37 5 may no longer make any sense to youWhat to logHere’s what you do n’t want to log:Everything!Specific methods only after an error has occurredHere’s what you do want to log:“Critical events,” such as updating a databaseResults of a long sequence of operationsInteractions with other components of a large systemActions known to be complex or error-proneWhen logging goes badHere’s an all-too-common error:Create log files on every run of the programNever get rid of old log filesSolution:Use the FileHandler class The FileHandler 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. Successively older files are named by adding "0", "1", "2", etc into the base filename.The rest of the storyAs usual, I’ve only given you a few features beyond the most basic usageIf you want to know about Filters, other destinations than the console or a file, etc., it’s all in the Java APIYou should also know that there is an alternative open source logging package, log4jlog4j has been around longer than Sun’s logging packageMany people feel that log4j is betterI didn’t cover it because it isn’t installed in the labs hereThe
View Full Document