A sample code that uses Java.util.logging.Logger for log output is as follows:
Package com.sample; Import Java.io.File; Import Java.util.logging.FileHandler; Import Java.util.logging.Handler; Import Java.util.logging.Level; Import Java.util.logging.Logger; Import Java.util.logging.SimpleFormatter; public class Loggersample {protected Logger Log=logger.getlogger (This.getclass (). GetName ()); public loggersample () {} public void SetHandler (Handler Handler) {This.log.addHandler (Handler);} public int Add (int a,int b) {int result=a+b; String l=a + "+" + B + "=" +result; Log.log (level.info,l); *1//Log.info (L); System.out.print (This.getclass (). GetName ()); return result; public static void Main (String [] args) {try{Logger Logg=logger.getlogger ("Com.sample.LoggerSample");//*2 Logg.setlevel (level.info);//*3 file F=new file ("C:/logger/log.log"); if (!f.exists ()) {New File ("C:/logger"). mkdir (); Filehandler fh = new Filehandler (f.tostring ());//*4 Fh.setformatter (New Simpleformatter ()); Consolehandler ch=new Consolehandler (); Ch.setlevel (Level.all); Loggersample ls=new loggersample (); Ls.sethandler (FH); Ls.add (1,2); Fh.close (); }catch (Exception e) {System.out.println ("Exception thrown:" +e); E.printstacktrace (); } } }
* 3: Set logger output level
Levels are listed in descending order as follows:
SEVERE (highest value)
WARNING
INFO
CONFIG
FINE
Finer
FINEST (lowest value)
In addition, there is a level off that you can use to turn off logging and enable logging of all messages using level all.
A log at a lower level, such as *1, will not be exported if the level of the setting is higher than the predefined output levels.
* 1 Places:
There are two ways to logger output:
①log.log (level.info, "message")
②log.info ("Mesage")
Other levels of output are similar to this.
* 2 places:
Gets the logger object for this class of com.sample.LoggerSample.
You can set its level so that when the loggersample runs, it will output the log based on the predefined levels in the loggersample.
* 4 places:
You can add handler to logger for different forms of output:
①filehandler: Output to File
②consolehandler: Output to console
③sockethandler: Output to Network