本文介绍了从两个不同的类中登录xml的正确方法是什么?目前,我在生成的xml中遇到错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认为代码:

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();
  }
}

产生以下类型的 xml :

<?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 :

But if I try to append to the xml produced above, by the following code :

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 中:

it appends the following to the previous xml produced :

<?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 时,出现以下错误:

and when I try opening this xml in the browser,I get the following error :

This page contains the following errors:

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

我该如何避免出现这种情况:

What do I do to avoid the statements :

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

两次?我希望 xml 仅在XML末尾附加 log 标记.

two times ? I want xml with just the log tag appended to the end of the xml.

推荐答案

RFE中列出了建议的补丁 JDK-4629315:追加XML日志文件不会合并新记录.您也许可以扩展XMLFormatter并覆盖 getHead 方法以有条件地写入默认头值或基于目标文件大小(空或完整)的空字符串.假设您可以计算当前用于日志记录的文件.

The proposed patch is listed in RFE JDK-4629315 : Appending of XML Logfiles doesn't merge new records. You might be able to extend XMLFormatter and override the getHead method to condtionally write the default head value or the empty string based off of the size (empty or full) of the target file. Assuming you can compute the current file being used for logging.

这篇关于从两个不同的类中登录xml的正确方法是什么?目前,我在生成的xml中遇到错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 20:39