2016-06-08 46 views
0

我正在使用SimpleFormatter编写日志文件。这些是用XML而不是纯文本编写的。我将它写成纯文本的答案都只是说使用简单的格式化程序(例如https://stackoverflow.com/a/10469185/651779)。这是我的自定义记录格式,从SimpleFormatter延伸:如何在Java中记录纯文本? SimpleFormatter还编写XML

class CustomRecordFormatter extends SimpleFormatter { 
    @Override 
    public String format(final LogRecord r) { 
     StringBuilder sb = new StringBuilder(); 
     sb.append(formatMessage(r)).append(System.getProperty("line.separator")); 
     if (null != r.getThrown()) { 
      sb.append("Throwable occurred: "); //$NON-NLS-1$ 
      Throwable t = r.getThrown(); 
      PrintWriter pw = null; 
      try { 
       StringWriter sw = new StringWriter(); 
       pw = new PrintWriter(sw); 
       t.printStackTrace(pw); 
       sb.append(sw.toString()); 
      } finally { 
       if (pw != null) { 
        try { 
         pw.close(); 
        } catch (Exception e) { 
         // ignore 
        } 
       } 
      } 
     } 
     return sb.toString(); 
    } 
} 

,这是我如何设置记录

public class DeconvolutionLogger { 
    static private FileHandler outfilePath; 
    protected final static Logger log = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); 
    static public void setup(String outputDir) throws IOException { 
    // get the global logger to configure it 
    log.setLevel(Level.INFO); 
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); 
    Date date = new Date(); 
    setOutfilePath(new FileHandler(outputDir+"/DeconvolutionLog_"+dateFormat.format(date)+".txt")); 
    CustomRecordFormatter customFormatter = new CustomRecordFormatter(); 
    ConsoleHandler consoleHandler = new ConsoleHandler(); 
    consoleHandler.setFormatter(customFormatter); 
    log.setUseParentHandlers(false); 
    log.addHandler(consoleHandler); 
    log.addHandler(outfilePath); 

    } 
} 

我缺少什么,它不写纯文本?

回答

2

outfilePath的格式化程序是stil XMLFormatter
您应该致电outfilePath.setFormatter(customFormatter);更改它。