Address: http://www.vogella.com/articles/Logging/article.html
Java Logging
This article describes how to use the logging API in JDK in a Java program. An example of creating an HTML logger is provided later.
Directory
-
1. Overview
-
-
1.1. Logging in Java
-
1.2. Create a logger
-
1.3. Log Level
-
1.4. Handler
-
1.5. formatter
-
1.6. Log Manager
-
1.7. Best practices
-
2. Example
-
3. Thank you
-
4. Questions and discussions
-
5. Related Article
1. overview1.1. logging in Java
The JDK contains the Java logging API. With logger, you can not only collect log information into a file to report errors, but also add auxiliary information to the log. This logging API allows you to customize and use flexibility.
1.2. Create a logger
The Java. util. Logging package provides the log function. You can use the code similar to the following to create a logger:
import java.util.logging.Logger;private final static Logger LOGGER = Logger.getLogger(MyClass.class .getName());
1.3. Level
The log level reflects the severity of the problem. The level class is used to determine which information is written into the log. Below is a log level sorted in descending order of Severity:
-
Severe (highest)
-
Warning
-
Info
-
Config
-
Fine
-
Finer
-
Finest
In addition, you can use the off or all levels to close logs or open all logs.
The following code sets logger to the info level of the record:
LOGGER.setLevel(Level.INFO);
1.4. Handler
You can set multiple handler for each logger.
Handler is used to receive logger information and send it to appropriate places in the appropriate format.
A handler can be disabled by setlevel (level. Off) and enabled by setlevel.
JDK provides several Standard handler, such:
Information that exceeds info is automatically written to the console.
1.5. formatter
Each handler output can be configured with a formatter.
Existing formatter:
You can also customize formatter. In the following example, formatter can encapsulate log information in HTML format:
package logging;import java.text.SimpleDateFormat;import java.util.Date;import java.util.logging.Formatter;import java.util.logging.Handler;import java.util.logging.Level;import java.util.logging.LogRecord;//This custom formatter formats parts of a log record to a single lineclass MyHtmlFormatter extends Formatter{// This method is called for every log recordspublic String format(LogRecord rec){StringBuffer buf = new StringBuffer(1000);// Bold any levels >= WARNINGbuf.append("<tr>");buf.append("<td>");if (rec.getLevel().intValue() >= Level.WARNING.intValue()){buf.append("<b>");buf.append(rec.getLevel());buf.append("</b>");} else{buf.append(rec.getLevel());}buf.append("</td>");buf.append("<td>");buf.append(calcDate(rec.getMillis()));buf.append(' ');buf.append(formatMessage(rec));buf.append('\n');buf.append("<td>");buf.append("</tr>\n");return buf.toString();}private String calcDate(long millisecs){SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");Date resultdate = new Date(millisecs);return date_format.format(resultdate);}// This method is called just after the handler using this// formatter is createdpublic String getHead(Handler h){return "<HTML>\n<HEAD>\n" + (new Date()) + "\n</HEAD>\n<BODY>\n<PRE>\n"+ "<table border>\n "+ "<tr><th>Time</th><th>Log Message</th></tr>\n";}// This method is called just after the handler using this// formatter is closedpublic String getTail(Handler h){return "</table>\n </PRE></BODY>\n</HTML>\n";}}
1.6. Log Manager
Log manager is responsible for creating and managing logger and maintaining log configuration.
Using the logmanager. setlevel (string name, level) method, we can set the logging level for a package or a group of packages. For example, we can
Level is set to level. fine:
LogManager.getLogManager().setLevel("logging", Level.FINE)
1.7. Best practices
Using the class named logger by logged is a good way for programmers to better view logs and manage logger. At the same time, this is also a recommended method for logging APIs.
2. For example, you can find this example in the project "De. vogella. Logger:
Create your own formatter:
package logging;import java.text.SimpleDateFormat;import java.util.Date;import java.util.logging.Formatter;import java.util.logging.Handler;import java.util.logging.Level;import java.util.logging.LogRecord;//This custom formatter formats parts of a log record to a single lineclass MyHtmlFormatter extends Formatter{// This method is called for every log recordspublic String format(LogRecord rec){StringBuffer buf = new StringBuffer(1000);// Bold any levels >= WARNINGbuf.append("<tr>");buf.append("<td>");if (rec.getLevel().intValue() >= Level.WARNING.intValue()){buf.append("<b>");buf.append(rec.getLevel());buf.append("</b>");} else{buf.append(rec.getLevel());}buf.append("</td>");buf.append("<td>");buf.append(calcDate(rec.getMillis()));buf.append(' ');buf.append(formatMessage(rec));buf.append('\n');buf.append("<td>");buf.append("</tr>\n");return buf.toString();}private String calcDate(long millisecs){SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");Date resultdate = new Date(millisecs);return date_format.format(resultdate);}// This method is called just after the handler using this// formatter is createdpublic String getHead(Handler h){return "<HTML>\n<HEAD>\n" + (new Date()) + "\n</HEAD>\n<BODY>\n<PRE>\n"+ "<table border>\n "+ "<tr><th>Time</th><th>Log Message</th></tr>\n";}// This method is called just after the handler using this// formatter is closedpublic String getTail(Handler h){return "</table>\n </PRE></BODY>\n</HTML>\n";}}
Initialize Logger
package logging;import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Formatter;import java.util.logging.Level;import java.util.logging.Logger;import java.util.logging.SimpleFormatter;public class MyLogger {static private FileHandler fileTxt;static private SimpleFormatter formatterTxt;static private FileHandler fileHTML;static private Formatter formatterHTML;static public void setup() throws IOException {// Create LoggerLogger logger = Logger.getLogger("");logger.setLevel(Level.INFO);fileTxt = new FileHandler("Logging.txt");fileHTML = new FileHandler("Logging.html");// Create txt FormatterformatterTxt = new SimpleFormatter();fileTxt.setFormatter(formatterTxt);logger.addHandler(fileTxt);// Create HTML FormatterformatterHTML = new MyHtmlFormatter();fileHTML.setFormatter(formatterHTML);logger.addHandler(fileHTML);}}
Use Logger
package logging;import java.io.IOException;import java.util.logging.Level;import java.util.logging.Logger;public class UseLogger {// Always use the classname, this way you can refactorprivate final static Logger LOGGER = Logger.getLogger(UseLogger.class.getName());public void writeLog() {// Set the LogLevel to Severe, only severe Messages will be writtenLOGGER.setLevel(Level.SEVERE);LOGGER.severe("Info Log");LOGGER.warning("Info Log");LOGGER.info("Info Log");LOGGER.finest("Really not important");// Set the LogLevel to Info, severe, warning and info will be written// Finest is still not writtenLOGGER.setLevel(Level.INFO);LOGGER.severe("Info Log");LOGGER.warning("Info Log");LOGGER.info("Info Log");LOGGER.finest("Really not important");}public static void main(String[] args) {UseLogger logger = new UseLogger();try {MyLogger.setup();} catch (IOException e) {e.printStackTrace();throw new RuntimeException("Problems with creating the log files");}logger.writeLog();}}