Logging
Logging
System.out.printlnstatements. Reportmessages >application >prgmer Report messages > application>prgmer Suppressandaddautomatic Suppressedlogscheap Logrecordsredirectiontohandlers Log records redirection to handlers Logrecordscanbefiltered Formattedindifferentways Useofmultipleloggers Use of multiple loggers
Loggers
Loggers are normally named entities, using Loggersarenormallynamedentities,using dotseparatednamessuchas"java.awt". The namespace is hierarchical and is managed Thenamespaceishierarchicalandismanaged bytheLogManager Loggerskeeptrackoftheirparentloggersin k k f h l theloggingnamespace
Logginglevel Handlers
RootLogger(named")hasnoparent.
packagecom.wombat; publicclassNose{ bli l N { //Obtainasuitablelogger. privatestaticLoggerlogger=Logger.getLogger("com.wombat.nose"); publicstaticvoidmain(Stringargv[]){ public static void main(String argv[]){ //LogaFINEtracingmessage logger.fine("doingstuff"); try{ Wombat.sneeze(); } catch(Errorex){ catch (Error ex){ //Logtheerrorlogger.log(Level.WARNING,"troublesneezing",ex); } logger.fine("done"); gg ( ); } }//morehierarchalthanpackages publicstaticvoidmain(String[]args){ bli i id i (S i [] ){ Handlerfh=newFileHandler("%t/wombat.log"); Logger.getLogger("").addHandler(fh); Logger.getLogger("com.wombat").setLevel("com.wombat",Level.FINEST); L tL (" b t") tL l(" b t" L l FINEST) ...}
packagecom.wombat; importjava.util.logging. ; import java util logging *; publicclassNose{ privatestaticLoggerlogger=Logger.getLogger("com.wombat.nose"); privatestaticFileHandlerfh new FileHandler("mylog.txt"); private static FileHandler fh =newFileHandler( mylog.txt ); publicstaticvoidmain(Stringargv[]){ //SendloggeroutputtoourFileHandler. logger.addHandler(fh);//Requestthateverydetailgetslogged. gg ( ); // q y g gg logger.setLevel(Level.ALL);//LogasimpleINFOmessage. logger.info("doingstuff"); try{ Wombat.sneeze(); } catch(Errorex){ logger.log(Level.WARNING,"troublesneezing",ex); } logger.fine("done"); } }
LoggingMethods gg g
Loggingmethodsfivecategories. Logmethod levelandmessage Log method level and message Defaultloggingconfiguration Infoorhigher
import java util logging Logger; java.util.logging.Logger; publicvoidlog(Level level,String msg) publicvoidlogp(Level level,String sourceClass,String sourceMethod,String public void logp(Level level, String sourceClass, String sourceMethod, String msg) GeneratelogrecordsoflevelFINERthatstartwithstringENTRYandRETURN publicvoidentering(String sourceClass,String sourceMethod) p publicvoidentering(String sourceClass,String sourceMethod,Object param1) g( g g j p ) Objectcanbearray.Similarlyexitingmethod. LogExceptions publicvoidlog(Level level,String msg,Throwable thrown)
void throwing(String sourceClass, String sourceMethod, Throwable thrown) Log throwing an exception.
Handlers
J2SE provides the following Handlers: StreamHandler: A simple handler for writing formatted records to an OutputStream. ConsoleHandler: A simple handler for writing formatted records to System.err (Default) FileHandler: A handler that writes formatted log records either to a single file, or to a set of rotating log files. SocketHandler: A handler that writes formatted log records to remote TCP g ports. MemoryHandler: A handler that buffers log records in memory. For a record to be logged its level must be above levels of both handler and logger. gg To log records at any level, set the levels of both handler and logger. Bypass configuration file and install custom handler public void setUseParentHandlers(boolean useParentHandlers)
Formatters
J2SEalsoincludestwostandardFormatters: SimpleFormatter: Writes brief "human SimpleFormatter:Writesbrief human readable"summariesoflogrecords. XMLF XMLFormatter:WritesdetailedXML W i d il d XML structuredinformation. AswithHandlers,itisfairlystraightforwardto developnewFormatters. develop new Formatters
FileHandlerhandler=newFileHandler(); Logger.addHandler(handler); FileHandler(String pattern,int limit,int count, boolean append) : Initialize a FileHandler to write to append):InitializeaFileHandlertowriteto asetoffileswithoptionalappend. javan log javan.log
public interface Filter A Filter can be used to provide fine grain control over what is logged, beyond the control provided by log levels levels. Each Logger and each Handler can have a filter associated with it The Logger or Handler will call the isLoggable method it. to check if a given LogRecord should be published. If isLoggable returns false, the LogRecord will be discarded. booleanisLoggable(LogRecord record) Checkifagivenlogrecordshouldbepublished.