0

我需要使用 Apache common simplelog 将日志写入文本文件,而不是将其打印到 System.err 中。

我在 write 方法中使用 FileWriter,它创建文件但不打印缓冲区中的数据。

protected void log(int type, Object message, Throwable t) {

    StringBuffer buf = new StringBuffer();


    if(showDateTime) {
        Date now = new Date();
        String dateText;
        synchronized(dateFormatter) {
            dateText = dateFormatter.format(now);
        }
        buf.append(dateText);
        buf.append(" ");
    }


    switch(type) {
        case SimpleLog.LOG_LEVEL_TRACE: buf.append("[TRACE] "); break;
        case SimpleLog.LOG_LEVEL_DEBUG: buf.append("[DEBUG] "); break;
        case SimpleLog.LOG_LEVEL_INFO:  buf.append("[INFO] ");  break;
        case SimpleLog.LOG_LEVEL_WARN:  buf.append("[WARN] ");  break;
        case SimpleLog.LOG_LEVEL_ERROR: buf.append("[ERROR] "); break;
        case SimpleLog.LOG_LEVEL_FATAL: buf.append("[FATAL] "); break;
    }


    if( showShortName) {
        if( shortLogName==null ) {

            shortLogName = logName.substring(logName.lastIndexOf(".") + 1);
            shortLogName =
                shortLogName.substring(shortLogName.lastIndexOf("/") + 1);
        }
        buf.append(String.valueOf(shortLogName)).append(" - ");
    } else if(showLogName) {
        buf.append(String.valueOf(logName)).append(" - ");
    }


    buf.append(String.valueOf(message));


    if(t != null) {
        buf.append(" <");
        buf.append(t.toString());
        buf.append(">");

        java.io.StringWriter sw= new java.io.StringWriter(1024);
        java.io.PrintWriter pw= new java.io.PrintWriter(sw);
        t.printStackTrace(pw);
        pw.close();
        buf.append(sw.toString());
    }


    write(buf);

}



protected void write(StringBuffer buffer) {

      System.err.println(buffer.toString());// want to print to a file rather than to err

     FileWriter file=new FileWriter(new File("d:/log.txt"));
     file.write(buffer.toString());   


}
4

2 回答 2

1

您需要刷新流

file.flush()

或者,如果您真的完成了对文件的写入,则需要关闭 writer。:

file.close()

close()在关闭之前刷新流。

于 2012-05-17T11:36:02.007 回答
0

This defeats the purpose of SimpleLog IMHO. If you want more complicated features, such as writing to a file instead of the console, you're better off plugging in log4j, or just use the jdk logging to back commons-logging. Either approach would keep the file writing options (file name, size limit, rollover, formatting) in configuration instead of in code.

于 2012-05-17T12:54:29.007 回答