0% found this document useful (0 votes)
75 views

Logging

The document discusses the basics of logging in Java, including: 1. Loggers are used to generate log records and are organized hierarchically. 2. Log levels determine the importance of log messages and include SEVERE, WARNING, INFO, etc. 3. Handlers are used to publish log records to their destination like files or the console.

Uploaded by

Acsh Sharma
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views

Logging

The document discusses the basics of logging in Java, including: 1. Loggers are used to generate log records and are organized hierarchically. 2. Log levels determine the importance of log messages and include SEVERE, WARNING, INFO, etc. 3. Handlers are used to publish log records to their destination like files or the console.

Uploaded by

Acsh Sharma
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

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

Basiclogging Basic logging


Logger.getLogger("global"); Logger.global.info(File Open menu selected); 14 Jan, 2012 11:07:24 AM ThreadDemo main INFO: File>Open menu selected File >Open Applications Logger objects. Loggers are organized in a hierarchical namespace and child Loggers may inherit log level from their parents in the namespace. Logger objects LogRecord Handler objects for publication. Both Loggers and Handlers may use logging Levels and (optionally) Filters. To publish a LogRecord externally, a Handler can (optionally) use a Formatter to localize and format the message before publishing it to an I/O stream.

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"); } }

LogLevels Log Levels


EachlogmessagehasanassociatedlogLevel importanceand urgencyofalogmessage. f l Loglevelobjectsencapsulateanintegervalue(finalandstaticfieldof Levelclass). ThefollowingliststheLogLevelsindescendingorder:
SEVERE(thehighestpriority,withthehighestvalue) WARNING INFO CONFIG FINE FINER FINEST(thelowestpriority,withthelowestvalue)

Defaulttopthreelevelsareactuallylogged. S l l allmsgs Setlevel ll LevelsOFF andALL

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.

voidwarning(StringsourceClass,StringsourceMethod,Stringmsg); id i (St i Cl St i M th d St i ) Caution:settingloglevelfinerthaninfo.

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.

LogManager Log Manager


singleglobalLogManagerobjectthatisused tomaintainasetofsharedstateabout Loggersandlogservices. public boolean addLogger(Logger logger) publicbooleanaddLogger(Logger publicLogger getLogger(String name)

ChangingLogManagerConfiguration Changing Log Manager Configuration


javaDjava.util.logging.config.file=myfile .level INFO (add your logger name) .level=INFO(addyourloggername) com.xyz.foo.level=SEVERE handlers=java.util.logging.ConsoleHandler java.util.logging.ConsoleHandler.level=INFO java util logging ConsoleHandler level = INFO java.util.logging.ConsoleHandler.formatter= java.util.logging.SimpleFormatter

You might also like