Java Logging API 生成空日志文件 [英] Java Logging API generating empty log files

查看:25
本文介绍了Java Logging API 生成空日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试阅读有关 Java 日志记录 API 的教程:

I tried to go through the tutorial on the Java logging API:

www.vogella.com/articles/Logging/article.html

www.vogella.com/articles/Logging/article.html

但是生成的文件是空的(在 Netbeans、Eclipse 以及从 cmd 运行 jar 中测试).日志消息仅显示在控制台中.

But the generated files are empty (tested in Netbeans, Eclipse as well as running the jar from cmd). The log messages are displayed in the console only.

以下是项目中用到的文件.这种行为的原因可能是什么?

The following are the files used in the project. What might be the reason for such behavior?

项目:de.vogella.logger

Project: de.vogella.logger

MyHtmlFormatter.java

MyHtmlFormatter.java

package de.vogella.logger;

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 line
class MyHtmlFormatter extends Formatter {
  // This method is called for every log records
  public String format(LogRecord rec) {
    StringBuffer buf = new StringBuffer(1000);
    // Bold any levels >= WARNING
    buf.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 created
  public String getHead(Handler h) {
    return "<HTML>\n<HEAD>\n" + (new Date()) 
        + "\n</HEAD>\n<BODY>\n<PRE>\n"
        + "<table width=\"100%\" border>\n  "
        + "<tr><th>Level</th>" +
        "<th>Time</th>" +
        "<th>Log Message</th>" +
        "</tr>\n";
  }

  // This method is called just after the handler using this
  // formatter is closed
  public String getTail(Handler h) {
    return "</table>\n  </PRE></BODY>\n</HTML>\n";
  }
}

MyLogger.java

MyLogger.java

package de.vogella.logger;

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 {

    // Get the global logger to configure it
    Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);

    logger.setLevel(Level.INFO);
    fileTxt = new FileHandler("Logging.txt");
    fileHTML = new FileHandler("Logging.html");

    // Create txt Formatter
    formatterTxt = new SimpleFormatter();
    fileTxt.setFormatter(formatterTxt);
    logger.addHandler(fileTxt);

    // Create HTML Formatter
    formatterHTML = new MyHtmlFormatter();
    fileHTML.setFormatter(formatterHTML);
    logger.addHandler(fileHTML);
  }
} 

UseLogger.java

UseLogger.java

package de.vogella.logger.test;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import de.vogella.logger.MyLogger;

public class UseLogger {
  // Always use the classname, this way you can refactor
  private final static Logger LOGGER = Logger.getLogger(UseLogger.class
      .getName());

  public void doSomeThingAndLog() {
    // Image here some real work

    // Now we demo the logging

    // Set the LogLevel to Severe, only severe Messages will be written
    LOGGER.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 written
    LOGGER.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 tester = new UseLogger();
    try {
      MyLogger.setup();
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException("Problems with creating the log files");
    }
    tester.doSomeThingAndLog();
  }
} 

推荐答案

更改以下行(在方法 de.vogella.logger.MyLogger.setup() 中):

Change the following line (in the method de.vogella.logger.MyLogger.setup()):

// Get the global logger to configure it
Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);

与:

// Get the global logger to configure it
Logger logger = Logger.getLogger("");

查看更多:

这篇关于Java Logging API 生成空日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆