我需要使用 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());
}