工作需要把Exception的内容打印到日志里,也就是把printStackTrace()输出的内容转到文本文件内。这个方法放在平时用的写log的静态类里方便使用。
public class LogUtil
{
public static void writeLog(final String str, final String name) throws IOException
{
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final SimpleDateFormat sdfFile = new SimpleDateFormat("yyyy-MM-dd");
final String logFile = System.getProperty("java.io.tmpdir");
final Date date = new Date();
final String _dateFile = sdfFile.format(date);
final String _date = sdf.format(date);
final String logName = logFile + File.separator + _dateFile + " " + name + ".log";
final File txt = new File(logName);
if (!txt.exists())
{
txt.createNewFile();
}
final FileOutputStream fos = new FileOutputStream(txt, true);
final OutputStreamWriter write = new OutputStreamWriter(fos, "UTF-8");
final BufferedWriter writer = new BufferedWriter(write);
writer.write(_date + " | ");
writer.write(str);
writer.close();
}
public static String logToString(final Exception e)
{
//将出错的栈信息输出到printWriter中
StringWriter stringWriter = null;
PrintWriter printWriter = null;
try
{
stringWriter = new StringWriter();
printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
printWriter.flush();
stringWriter.flush();
}
finally
{
if (stringWriter != null)
{
try
{
stringWriter.close();
}
catch (final IOException e1)
{
e1.printStackTrace();
}
}
if (printWriter != null)
{
printWriter.close();
}
}
return stringWriter.toString();
}
}