1

默认情况下,代码:

class Tester {
  public static void main(String args[]) throws IOException{
    Logger logger = Logger.getLogger(Tester.class.getName());
    FileHandler fHandler = new FileHandler("LOGGED.xml",true);
    logger.addHandler(fHandler);
    logger.log(Level.INFO,"This is an info log message");
    fHandler.close();
  }
}

产生 axml的类型:

<?xml version="1.0" encoding="windows-1252" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
  <record>
    <date>2013-02-03T08:16:37</date>
    <millis>1359859597763</millis>
    <sequence>0</sequence>
    <logger>Tester</logger>
    <level>INFO</level>
    <class>Tester</class>
    <method>main</method>
    <thread>1</thread>
    <message>This is an info log message</message>
 </record>
</log>

但是,如果我尝试通过以下代码附加到上面生成的xml中:

class Tester_1{
public static void main(String args[]) {
    try {
        Logger logger = Logger.getLogger(Tester_1.class.getName());
        FileHandler fHandler = new FileHandler("LOGGED.xml",true);
        logger.addHandler(fHandler);
        logger.log(Level.INFO,"This is a custom message from my own formatter !");
        fHandler.close();
    }catch(Exception exc) {
        exc.printStackTrace();
    }
}

}

它将以下内容附加到先前生成的xml中:

<?xml version="1.0" encoding="windows-1252" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
 <record>
   <date>2013-02-03T08:16:51</date>
   <millis>1359859611306</millis>
   <sequence>0</sequence>
   <logger>Tester_1</logger>
   <level>INFO</level>
   <class>Tester_1</class>
   <method>main</method>
   <thread>1</thread>
   <message>This is a custom message from my own formatter !</message>
 </record>
</log>

当我尝试在浏览器中打开此xml时,出现以下错误:

This page contains the following errors:

error on line 27 at column 6: XML declaration allowed only at the start of the document

我该怎么做才能避免这些陈述:

<?xml version="1.0" encoding="windows-1252" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">

两次?我想要只在xmllog末尾附加标签的 xml。

4

3 回答 3

1

如果您想在日志文件中完全避免 xml 标头,您可以在代码中尝试此操作

    FileHandler fHandler = new FileHandler("LOGGED.xml", true);
    fHandler.setFormatter(new XMLFormatter() {
        @Override
        public String getHead(Handler h) {
            return "";
        }
    });
    logger.addHandler(fHandler);
于 2013-02-03T04:15:37.310 回答
0

修复它的简单方法是将 FileHandler 配置为每次启动应用程序时生成一个新文件名,例如

new FileHandler("log%g.xml", 100000000, 10);

详见 API

于 2013-02-03T03:55:17.580 回答
0

提议的补丁列在 RFE JDK-4629315 中:附加 XML 日志文件不会合并新记录。 您可能能够扩展 XMLFormatter 并覆盖该getHead方法以根据目标文件的大小(空或满)有条件地写入默认头值或空字符串。假设您可以计算用于记录的当前文件。

于 2013-08-01T15:36:12.203 回答