的Logger类提供setLevel()给设置日志级别方法。通过将日志记录设置为特定级别,我们可以控制要记录的消息。
要确定或检查是否将记录一条消息,我们可以使用该Logger.isLoggable(Level level)方法。让我们看下面的例子。
package org.nhooo.example.util.logging; import java.util.logging.Logger; import java.util.logging.Level; public class LoggingLevelCheck { public static void main(String[] args) { // 获取Logger的实例并将日志记录级别设置为 // 级别警告。 Logger log = Logger.getLogger(LoggingLevelCheck.class.getName()); log.setLevel(Level.WARNING); //日志信息级别的消息。由于以下原因,将不会记录此消息 // 日志级别设置为“级别”。警告 if (log.isLoggable(Level.INFO)) { log.info("Application Information Message"); } // 当Level.WARNING可记录时,记录WARNING级别消息。 if (log.isLoggable(Level.WARNING)) { log.warning("Application Warning Information"); } // 当Level.SEVERE可记录时,记录SEVERE级别消息。 if (log.isLoggable(Level.SEVERE)) { log.severe("Information Severe Information"); } } }
这将仅记录Level.WARNING和Level.SEVERE消息。
04 Dec 18 13:49:58 org.nhooo.example.util.logging.LoggingLevelCheck main WARNING: Application Warning Information04 Dec 18 13:49:58 org.nhooo.example.util.logging.LoggingLevelCheck main SEVERE: Application Severe Information